While going through the book Scala for the Impatient, I came across this question:
Come up with one situation where the assignment x = y = 1 is valid in Scala. (Hint: Pick a suitable type for x.)
I am not sure what exactly the author means by this question. The assignment doesn't return a value, so something like var x = y = 1
should return Unit() as the value of x. Can somebody point out what might I be missing here?
Thanks
On Scala Collections there is usually :+ and +: . Both add an element to the collection. :+ appends +: prepends. A good reminder is, : is where the Collection goes. There is as well colA ++: colB to concat collections, where the : side collection determines the resulting type.
In the above syntax, the variable can be defined in one of two ways by using either the 'var' or 'val' keyword. It consists of 'variable_name' as your new variable, followed by a colon. The data type of variable is 'variable_datatype. ' which can be any valid data type.
Use the with Keyword in ScalaThis keyword is usually used when dealing with class compositions with mixins. Mixins are traits that are used to compose a class. This is somewhat similar to a Java class that can implement an interface.
In fact, x
is Unit
in this case:
var y = 2
var x = y = 1
can be read as:
var y = 2
var x = (y = 1)
and finally:
var x: Unit = ()
You can get to the point of being able to type x=y=1
in the REPL shell with no error thus:
var x:Unit = {}
var y = 0
x = y = 1
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