简体   繁体   English

x = y = 1 在 Scala 中?

[英]x = y =1 in Scala?

While going through the book Scala for the Impatient , I came across this question:为 Impatient 阅读 Scala这本书时,我遇到了这个问题:

Come up with one situation where the assignment x = y = 1 is valid in Scala. (Hint: Pick a suitable type for x.)想出一种情况,赋值 x = y = 1 在 Scala 中有效。(提示:为 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.赋值不返回值,所以类似var x = y = 1的东西应该返回 Unit() 作为 x 的值。 Can somebody point out what might I be missing here?有人可以指出我在这里可能会遗漏什么吗?

Thanks谢谢

In fact, x is Unit in this case:实际上,在这种情况下xUnit

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:您可以在 REPL shell 中输入x=y=1而不会出现错误:

var x:Unit = {}
var y = 0
x = y = 1

Here's another less known case where the setter method returns its argument.这是另一个鲜为人知的案例,其中 setter 方法返回其参数。 Note that the type of x is actually Int here:请注意,这里x的类型实际上是Int

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 .) (此功能在 XScalaWT 库中使用,并在该问题中进行了讨论。)

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM