相关疑难解决方法(0)

在Scala中,为什么我可以在这里使用`Unit`作为返回类型?

代码如下:

scala> def f(x:Int => Unit):Unit = 1
<console>:7: warning: a pure expression does nothing in statement position; you may be omitting necessary parentheses
       def f(x:Int => Unit):Unit = 1
                                   ^
f: (x: Int => Unit)Unit

scala> f(_=>2);
<console>:9: warning: a pure expression does nothing in statement position; you may be omitting necessary parentheses
              f(_=>2);
                   ^

scala> f(_=>List(1,2));
Run Code Online (Sandbox Code Playgroud)

上面的所有三个表达式都在REPL中工作(有一些警告),但它们看起来有点令人困惑.

在第一个表达式中,f's返回类型是Unit,AnyVal但是不是Supertype 的子类型Int,因此,我无法理解为什么1可以用作返回值.

在第二个表达式中,_=>2也使用2而不是Unit作为返回值,它与定义冲突.

在第三个表达式中,_=> …

java types functional-programming scala type-inference

3
推荐指数
1
解决办法
336
查看次数