Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why parentheses around int on a scala method invocation

Tags:

scala

I'm going through a Scala tutorial, and it's explaining that all operators are actually method invocations. So 1 * 2 is really:

scala> (1).*(2)
res1: Int = 2

Just to see what would happen, I ran:

scala> 1.*(2)
warning: there were 1 deprecation warning(s); re-run with -deprecation for details
res2: Double = 2.0

So I run it again with the deprecation flag and I get:

scala> 1.*(2)
<console>:1: warning: This lexical syntax is deprecated.  From scala 2.11, a dot will only be considered part of a number if it is immediately followed by a digit.
       1.*(2)

Could someone please explain this warning to me, and also explain to me what purpose the parentheses around the 1 in scala> (1).*(2) serve?

like image 288
mistahenry Avatar asked Jan 12 '14 21:01

mistahenry


People also ask

What is the meaning of => in Scala?

=> is syntactic sugar for creating instances of functions. Recall that every function in scala is an instance of a class. For example, the type Int => String , is equivalent to the type Function1[Int,String] i.e. a function that takes an argument of type Int and returns a String .

What is the difference between method and function in Scala?

Difference between Scala Functions & Methods: Function is a object which can be stored in a variable. But a method always belongs to a class which has a name, signature bytecode etc. Basically, you can say a method is a function which is a member of some object.

What is the syntax of defining method in Scala?

Scala doesn't allow us to define an anonymous method. We have to use a special keyword def for method definition: def inc(number: Int): Int = number + 1. We can define a method's list of parameters in parentheses after its name.


1 Answers

When you say 1.*(2) it's ambiguous as to whether you mean:

(1).*(2), which results in an Int

or

(1.)*(2), which results in a Double, since 1. is valid syntax meaning the Double 1.0

Scala currently treats it as the second one, but since the correct behavior isn't obvious, it will be changing from Scala 2.11 onwards to treat it like the first one. Scala warns you that its behavior will change.

like image 108
dhg Avatar answered Sep 28 '22 05:09

dhg