【发布时间】:2016-02-10 21:03:01
【问题描述】:
我最近开始学习 scala,但在尝试“打印”单元格时偶然发现了一个问题:
class Cell(
val x: Int,
val y: Int,
val left: Option[Cell],
val right: Option[Cell],
val top: Option[Cell],
val bottom: Option[Cell],
var isPainted: Boolean) {
def paint(radius: Int) = {
println("Printing")
if (radius == 0)
isPainted = true
else {
isPainted = true
top.isPainted = true
bottom.isPainted = true
left.isPainted = true
right.isPainted = true
为什么这些相邻的单元格
top.left.paint(r - 1)
top.right.paint(r - 1)
bottom.left.paint(r - 1)
bottom.right.paint(r - 1)
无法访问?
}
}
如何访问顶部、底部、左侧、右侧的单元格?
编辑:
感谢您的出色回答。 一个附加问题:
如何检查单元格 x 周围的所有单元格是否都设置为 true? 不幸的是,我的尝试不起作用。
def isMiddleCell()={
if(List(top, bottom, left, right).forall(_.Some))
true
else
false
}
【问题讨论】:
-
因为他们不是
Cells,他们是Option[Cell]。阅读Options。 -
所以如果我理解正确,
.get()需要被称为类似于:val ttop = top.getOrElse("No top neighbour") ttop.isPainted = true top.getOrElse("No top neighbour").isPainted = true但是这两个都不起作用。即使将true包裹在Some(true)中也不起作用。
标签: scala