That code will not compile, because for someVal
to be a String, then each execution path (the if
and the else
) would have to return a String. However since you don't have an else
, this is impossible and thus won't compile.
The compiler error will be the following, which is indicating that you are returning a Unit
when you are supposed to return String
:
error: type mismatch;
found : Unit
required: String
That's because what you have is equivalent to this:
val someVal: String = if (foo == bar) "Hello World" else ()
()
is the only value of Unit, which is not a valid value for a String type.
In the future you can use the Scala repl and have it tell you the types (just don't specify one):
scala> val someVal1 = if (true) "Hello World"
someVal1: Any = Hello World
val someVal2 = if (false) "Hello World"
someVal2: Any = ()
As you can see the type is Any
because that is the only common parent between Unit
and String
:
