Unlike C # (both Java and C and C ++), which are operator-based languages, Scala is an expression-based language. This is basically a big plus in terms of composability and readability, but in this case the difference bit you.
The Scala method implicitly returns the value of the last expression in the method
scala> def id(x : String) = x id: (x: String)String scala> id("hello") res0: String = hello
In Scala, almost everything is an expression. Things that look like statements are still expressions that return a value of type Unit. The value can be written as ().
scala> def foo() = while(false){} foo: ()Unit scala> if (foo() == ()) "yes!" else "no" res2: java.lang.String = yes!
No compiler for the Turing equivalent language can detect all infinite loops (cf the problem of stopping Turing), so most compilers work very little to detect them. In this case, the type "while (someCondition) {...}" is a unit, regardless of what someCondition is, even if it is true.
scala> def forever() = while(true){} forever: ()Unit
Scala determines that the declared return type (String) is incompatible with the actual return type (Unit), which is the type of the last expression (while ...)
scala> def wtf() : String = while(true){} <console>:5: error: type mismatch; found : Unit required: String def wtf() : String = while(true){}
Answer: add an exception to the end
scala> def wtfOk() : String = { | while(true){} | error("seriously, wtf? how did I get here?") | } wtfOk: ()String
James ry
source share