【发布时间】:2014-04-21 21:18:29
【问题描述】:
我对以下 Scala 编译器行为很感兴趣。当我声明一个单元类型的函数,但仍然提供一个评估为 Int 的函数作为主体时,Scala 编译器可以接受。
def add(x:Int, y:Int) = x + y
def main(args: Array[String]): Unit = {add(args(0).toInt, args(0).toInt)}
虽然其他类型的情况并非如此
def afunc: String = {1} //type mismatch; found : Int(1) required: String
如果我写了
def afunc: Unit = {1}
或
def main(args: Array[String]): Unit = {2 + 2} // Which is just like the first addition above
在这两种情况下,我都会收到以下警告:
a pure expression does nothing in statement position; you may be omitting necessary parentheses
从某种意义上说,这里有两个问题。返回计算结果为 Int 的函数和表达式 2 + 2 之间有什么区别。那么,究竟为什么编译器不会抱怨假设计算结果为 Unit 的函数会得到一个计算结果为另一种类型的主体,因为它会发生在其他类型之间。
非常感谢,
马塔里
【问题讨论】:
标签: scala functional-programming