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.
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.
=> 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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With