I have the following code:
class Animal(hair: Option[Hair])
class Cat(var hair: Option[Hair]) extends Animal(hair)
class Dog(var hair: Option[Hair]) extends Animal(hair)
class Sheep(var hair: Option[Hair]) extends Animal(hair)
//then somewhere else:
def what(animal: Animal) {
animal match {
case Cat(hair) => println("processing cat, hair=" + hair)
case Dog(hair) => println("processing dog, hair=" + hair)
case Sheep(hair) => {
println("processing sheep, cutting hair...")
hair = None
}
}
}
问题如下:
1)当模式匹配成功时,如何访问Sheep的毛并更改它?它抱怨对val的重新赋值,于是我在构造函数中放置了var,但仍然……
2)我能想到的另一种方法是将整个匹配的值分配给一个变量,有没有办法将由某个case类构造函数模式匹配的值绑定到一个变量上?
(我知道我可能可以在像s:Sheep这样的东西上进行模式匹配,然后调用s.changeHairTo(None),但那是最不理想的方式)。