Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

scala

What the difference between the two defs below

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

AND

def someFun(x:String) = { x.length } 
like image 388
Soumya Simanta Avatar asked Dec 01 '22 16:12

Soumya Simanta


1 Answers

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 {}
<console>: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.

like image 190
Gabriele Petronella Avatar answered Dec 18 '22 10:12

Gabriele Petronella