What is return type of `if` statement

前端 未结 3 1205
温柔的废话
温柔的废话 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: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 = ()
    

提交回复
热议问题