What is return type of `if` statement

前端 未结 3 1195
温柔的废话
温柔的废话 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.

    0 讨论(0)
  • 2020-12-21 08:42

    if (cond) { expr } returns common base type of Unit and type of expr, just like if (cond) { expr } else { () }.

    It is AnyVal for Int, Char and so on, Unit for Unit and Any for AnyRef:

    scala> if ( false ) 1
    res0: AnyVal = ()
    
    scala> val r = if ( false ) { () }
    r: Unit = ()
    
    scala> if ( false ) ""
    res1: Any = ()
    
    0 讨论(0)
  • 2020-12-21 08:44

    The if statement takes a statement/closure/variable. When using closures, the final statement is used to infer the type. Since configFile.getAbsolutePath() is a function evaluating to String. Unit subclasses Any meaning either of the following works:

    val configFilePath:Any = if (configFile.exists()) {configFile.getAbsolutePath()}
    

    and

    val configFilePath:Unit = if (configFile.exists()) {configFile.getAbsolutePath()}
    

    Edit

    The case may be that the condition is evaluating to false for instance

    val map = Map(1 -> "1")
    val result = if(map.get(2)=="1") "Whoopie!"
    

    result here would be type Any = () since there is no else and the value either doesn't exist or the value is not equal to 1 This would be more appropriate if you wish for the type to be String

    val configFilePath = if (configFile.exists()) {configFile.getAbsolutePath()} else ""
    
    0 讨论(0)
提交回复
热议问题