Scala高阶函数中未声明变量n为何被推断为String类型?
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
sayHelloreturns a function of typeString => 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 typeStringand return aString. - String interpolation reinforces consistency: The expression
s"$prefix $n"combinesprefix(which we know is aString) withn. For this interpolation to work seamlessly and produce the requiredStringoutput (per the return type),nhas to be aString—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
sayHelloreturns a function expecting aStringinput, it infers thatnmust be aStringto satisfy that requirement. The string interpolation then confirms this is valid, as it produces theStringoutput 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

