You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Scala匿名函数调用疑问:为何输出"hello there"?

问题解答

咱们一步步拆解这段代码的执行逻辑,你就能明白"there"是怎么拼进去的了:

  1. saySomething是个「返回函数的函数」
    定义里的def saySomething(prefix: String) = (s: String) => { prefix + " " + s },意思是:

    • 给它传一个prefix(比如"hello"),它会返回一个新的匿名函数
    • 这个新函数的作用是:接收一个字符串s,然后把prefix和s用空格拼起来
  2. saySomethingElse是绑定了prefix="hello"的匿名函数
    当执行saySomething("hello")时,prefix被固定成了"hello",返回的匿名函数被赋值给saySomethingElse。此时saySomethingElse等价于:

    (s: String) => { "hello" + " " + s }
    
  3. 调用saySomethingElse("there")就是给匿名函数传参
    这一步把s设为"there",代入上面的逻辑,自然得到"hello" + " " + "there",也就是"hello there"。

简单说,saySomething是个「函数工厂」,给它不同的prefix就能生成不同的拼接函数;saySomethingElse是工厂造出的、预设好prefix的拼接工具,最后传"there"就是完成最终拼接。

内容的提问来源于stack exchange,提问作者Augusto Valbuena

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 09:21:01