3

Being relatively new at Scala, I was playing around with partially-applied function syntax on sbt console. I ran into a very weird issue in which I do not understand Scala's behavior.

The example is contrived and would unlikely be encountered in reality. That said, here it is. Suppose I define the following function:

scala> def f(x: Int, y: Int) = "%d %d".format(x, y)

Now if I type in

scala> f(1, _:Int)(2)
res: Int => Char = <function1>

The result is a Int => Char function, which is very unusual. In other words, Scala is (temporarily) treating f(1, _:Int) as a String (vs. its actual type: Int => String) when applying the parameter (i.e., 2).

If, instead, parentheses are used, what I expect to happen occurs:

scala> (f(1, _:Int))(2)
res: String = 1 2

However, this does not appear to be an order-of-operations issue, as I cannot find a way to add parentheses to achieve the unexpected behavior (i.e., having the result be of type Int => Char).

Any ideas?

4

1 回答 1

2

首先关于结果类型:

scala> f(1, _:Int)(2)
res: Int => Char = <function1>

看一下这个:

scala> val str = "hello"
str: String = hello

scala> str(2)
res12: Char = l

我认为这很清楚。

对功能本身不,因为它也很容易。当您将它提升到带有下划线的函数时,您不仅会提升f,而且还会调用(2)字符串(第一个结果),这就是您得到的原因:

res: Int => Char = <function1>

添加

更明确的版本。您的函数f是 type (Int, Int) => String,当您编写时f(1, _: Int),您将其部分应用于参数 one 并返回 type 的函数Int => String,其中Int是第二个参数。然后你的参数(2)调用方法从返回你apply的函数的结果字符串,从这里你得到类型的函数,其中是你的函数的第二个参数,是结果字符串中的一个字符Int => StringCharInt => CharIntfChar

在第二种情况下,您有:

scala> (f(1, _:Int))(2)
res: String = 1 2

通过括号,您将其拆分为多个事物,第一个是一个函数Int => String(2)调用此函数,您将一个参数传递2给此函数Int => String

val ff = f(1, _: Int)
val res = ff(2)
于 2013-10-03T20:47:25.127 回答