I found that it\'s a shame that I can\'t return a return value from a such simple construction as try ... catch ... finally
def foo: String = {
This is happening because in Scala unlike Java, try-catch are expressions. In your code, try block returns a String
and your catch block return type is Unit
(as you are just printing and returning nothing).
The type-inference hence takes the return type T
such that T >: Unit
and T >: String
. Hence T
is of type Any
. And because you have declared foo as def foo: String
. The compiler throws an error as it was expecting String but found Any.
What you can do is to return a default value under you catch block:
try{
in.readLine
}
catch {
case e: IOException => {
e.printStackTrace()
"error string"
}
}
finally{
in.close
}