Using "if" as an expression

I wonder why I can not compile this file:

class MyClass{ override def toString = "123:" + if (true) "456" else "789" //error: illegal start of simple expression } 
+4
source share
2 answers

Try the following:

 override def toString = "123:" + (if (true) "456" else "789") 
+10
source

pedrofurla is right. With your expression, the compiler is trying to mix the string with if and fail. Using parentheses, you eliminate the ambiguity in your expressions.

 class MyClass{ override def toString = "123:" + (if (true) "456" else "789") } 

I found this simple online service where you can test scala expressions: http://www.simplyscala.com/

0
source

Source: https://habr.com/ru/post/1487674/


All Articles