Try … catch … finally return value

后端 未结 4 1679
心在旅途
心在旅途 2021-02-07 01:24

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 = {
            


        
4条回答
  •  盖世英雄少女心
    2021-02-07 02:06

    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
     }
    

提交回复
热议问题