Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

x = y =1 in Scala?

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

like image 620
sc_ray Avatar asked Apr 09 '12 17:04

sc_ray


People also ask

What does +: mean in Scala?

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.

How do you declare a variable in Scala?

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.

What is with in Scala?

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.


2 Answers

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 = ()
like image 59
Tomasz Nurkiewicz Avatar answered Oct 13 '22 21:10

Tomasz Nurkiewicz


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
like image 27
timday Avatar answered Oct 13 '22 19:10

timday