Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this Scala code with assignment of a val in a parameter working?

Tags:

scala

object Main {

  def main(args: Array[String])
  {
    val x = 10
    print(x="Hello World")
    print(x)
  }
}

output : Hello World10

As we know, in Scala a val cannot be reassigned or changed, but here x is changing to

Hello World

while printing.

like image 622
Deepak Pandey Avatar asked Mar 13 '18 07:03

Deepak Pandey


People also ask

Can Val be reassigned in Scala?

In Scala, reassignment to val is not allowed, but we can create a new val and assign the value to it. We can see an error when reassigning the values to a val . As a workaround, we can assign the result to a new val and use it. Scala provides us with three ways to define things.

What does => mean in Scala?

=> is the "function arrow". It is used both in function type signatures as well as anonymous function terms. () => Unit is a shorthand for Function0[Unit] , which is the type of functions which take no arguments and return nothing useful (like void in other languages).


1 Answers

Explanation is kind of unexpected: print has a parameter named x. Using x = ... uses the named argument, therefore print(x="Hello World") is the same as print("Hello World").

See Scala Predef docs or Predef.scala source:

object Predef /*....*/ {

/*....*/
  def print(x: Any) = Console.print(x)

/*....*/
}

Note: this was already discussed in Scala Internal mailing list:

Scala currently tries to be smart about treating "x = e" as a named argument or an assignment ... This can be surprising to the user ....

Proposal: we deprecate assignments in argument lists

There also exists an issue SI-8206 for this, the change was probably implemented in issue 426 for Scala 2.13.

Your code will still compile after deprecation, with the same meaning. The change will be no one (at least no one sufficiently familiar with the language specs / implementation) should expect it to be interpreted as assignment any more.

like image 120
Suma Avatar answered Oct 11 '22 19:10

Suma