14

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

sc_ray
  • 7,803
  • 11
  • 63
  • 100
  • I strongly suspect that the author was *not* thinking of x as of Unit type - that by "valid", they meant to imply "and have some purpose". – Ed Staub Apr 10 '12 at 17:20

5 Answers5

13

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 = ()
Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
6

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
timday
  • 24,582
  • 12
  • 83
  • 135
3

Here’s another less known case where the setter method returns its argument. Note that the type of x is actually Int here:

object AssignY {
  private var _y: Int = _
  def y = _y
  def y_=(i: Int) = { _y = i; i }
}

import AssignY._

var x = y = 1

(This feature is used in the XScalaWT library, and was discussed in that question.)

Community
  • 1
  • 1
Jean-Philippe Pellet
  • 59,296
  • 21
  • 173
  • 234
  • 1
    Clearly, this is not what I had in mind :-) But if you want weird solutions, how about `implicit def unit2int(u: Unit) = 42; var x = 1; var y = 2; x = y = 1` – cayhorstmann Jun 12 '12 at 15:35
1

BTW if assigning of the same value to both variables still required then use:

scala> var x@y = 1
x: Int = 1
y: Int = 1
Andriy Plokhotnyuk
  • 7,883
  • 2
  • 44
  • 68
0

It's valid, but not sensible, this make confusion.

scala> var x=y=1
x: Unit = ()

scala> y
res60: Int = 1

scala> var x@y = 1
x: Int = 1
y: Int = 1
G.J Zhao
  • 1
  • 1