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

Scala高阶函数中未声明变量n为何被推断为String类型?

Why Scala Infers n as String in This Higher-Order Function

Great question—let’s break this down piece by piece to connect the dots between the higher-order function’s return type and the inferred type of n.

First, let’s restate your code clearly for reference:

def sayHello(prefix: String): (String => String) = { n => s"$prefix $n" }
val greeting = sayHello("Hello")
greeting("Gio")

Here’s the step-by-step reasoning behind the type inference:

  • The return type sets a hard constraint: You’ve explicitly declared that sayHello returns a function of type String => String. That means the anonymous function you’re returning (n => s"$prefix $n") must exactly match this signature: it has to take one parameter of type String and return a String.
  • String interpolation reinforces consistency: The expression s"$prefix $n" combines prefix (which we know is a String) with n. For this interpolation to work seamlessly and produce the required String output (per the return type), n has to be a String—Scala doesn’t need to guess here because the return type already tells it what input type the anonymous function must accept.
  • The compiler ties it all together: Scala’s type inference works hand-in-hand with explicit type declarations. Since you’ve told the compiler that sayHello returns a function expecting a String input, it infers that n must be a String to satisfy that requirement. The string interpolation then confirms this is valid, as it produces the String output the return type demands.

To make this even more concrete, try changing the return type of sayHello to Int => String:

def sayHello(prefix: String): (Int => String) = { n => s"$prefix $n" }

Now n will be inferred as Int—all because the return type constraint now requires the input to be an Int, and the string interpolation can still convert that Int to a String for the output.

In short, the explicit return type of your higher-order function gives the compiler the context it needs to lock in n’s type as String.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:09:21