What's the difference between using and no using a “=” in Scala defs ?

后端 未结 5 694
情歌与酒
情歌与酒 2021-01-21 11:06

What the difference between the two defs below

def someFun(x:String) { x.length } 

AND

def someFun(x:String) = {          


        
5条回答
  •  再見小時候
    2021-01-21 11:42

    Without the equals it is implicitly typed to return Unit (or "void"): the result of the body is fixed - not inferred - and any would-be return value is discarded.

    That is, def someFun(x:String) { x.length } is equivalent to def someFun(x:String): Unit = { x.length }, neither of which are very useful here because the function causes no side-effects and returns no value.

    The "equals form" without the explicit Unit (or other type) has the return type inferred; in this case that would be def someFun(x:String): Int = { x.length } which is more useful, albeit not very exciting.


    I prefer to specify the return type for all exposed members, which helps to ensure API/contract stability and arguably adds clarity. For "void" methods this is trivial done by using the Procedure form, without the equals, although it is a stylistic debate of which is better - opponents might argue that having the different forms leads to needless questions about such ;-)

提交回复
热议问题