What is return type of `if` statement

前端 未结 3 1196
温柔的废话
温柔的废话 2020-12-21 08:05

From Programming Scala book I read that in following code configFilePath constant will be type of Unit:

scala> val configFilePat         


        
3条回答
  •  不知归路
    2020-12-21 08:23

    As always, an if statement evaluates a logical condition and has to return a logical result. Therefore: scala.Boolean. But the value is not in a return per say. The result of the evaluation is used in execution, but as you are doing it:

    val configFilePath = if (configFile.exists()) {
        configFile.getAbsolutePath();// say this returns a String.
    };
    

    But what if that configFile.exists() returns false? Nothing will be placed into that variable, therefore the compiler will infer the type to Any, which makes sense since you provided no way to conclude the type.

    Also, you are probably better off using match.

    val configFilePath = configFile.exists match {
        case true => Some { configFile.getAbsolutePath }
        case false => None
    };
    

    The above is deterministic and should return an Option[ReturnType], which is the default Scala way of handling such things.

提交回复
热议问题