Reputation: 4662
I am learning Scala programming language, and got confused by this:
var set = Set("hello", "world")
set += "Tom"
println(set)
println(set += "Tom")
The first print will output
Set(hello, world, Tom)
But the second will output
()
So, why they are different, I thought println(set += "Tom")
will first do, set += "Tom"
, and then print its result? Isn't it?
Upvotes: 1
Views: 64
Reputation: 20435
As already answered by @pedrofurla, the second print displays the result of evaluating the assignment, namely the Unit
denoted with ()
.
In addition, note we can print the result of evaluating the following block delimited by curly brackets,
println( {set += "Tom" ; set} )
Set(hello, world, Tom)
namely, add "Tom"
to set
as the first expression, then deliver the updated set
as the final result of the block evaluation.
Upvotes: 1
Reputation: 12783
In scala a += b
dessugars to a = a + b
. The type of assignment expression is Unit. So, unlike C or Java, the result of an assignment expression doesn't result in the left-hand side but in the Unit value.
Upvotes: 5