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

后端 未结 5 729
情歌与酒
情歌与酒 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:49

    As others already pointed out, the former is a syntactic shortcut for

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

    Meaning that the value of x.length is discarded and the function returns Unit (or () if you prefer) instead.

    I'd like to stress out that this is deprecated since Oct 29, 2013 (https://github.com/scala/scala/pull/3076/), but the warning only shows up if you compile with the -Xfuture flag.

    scala -Xfuture -deprecation
    
    scala> def foo {}
    :1: warning: Procedure syntax is deprecated. Convert procedure `foo` to method by adding `: Unit =`.
           def foo {}
    foo: Unit
    

    So you should never use the so-called procedure syntax. Martin Odersky itself pointed this out in his Scala Day 2013 Keynote and it has been discussed in the scala mailing list.

    The syntax is very inconsistent and it's very common for a beginner to hit this issue when learning the language. For this reasons it's very like that it will be removed from the language at some point.

提交回复
热议问题