Scala - 在模式匹配中指定匹配项

non*_*com 8 binding scala pattern-matching

我有以下代码:

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
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

问题是:

1)当模式匹配与绵羊成功时,我怎样才能进入它的头发并改变它?它抱怨重新分配给val,然后我把它放在var构造函数中但仍然......

2)我能想到的另一种方法是将整个匹配值分配给变量,有没有办法将一些case类构造函数模式匹配的值绑定到变量?

(我知道我可能会在类似的东西上进行模式匹配s: Sheep然后调用,s.changeHairTo(None)但这是最不可取的方式).

4e6*_*4e6 25

您可以使用@将整个模式绑定到版本中的变量

class Animal(hair: Option[Hair])
case class Cat(var hair: Option[Hair]) extends Animal(hair)
case class Dog(var hair: Option[Hair]) extends Animal(hair)
case class Sheep(var hair: Option[Hair]) extends Animal(hair)

def what(animal: Animal) {
  animal match {
    case Cat(hair) => println("processing cat, hair=" + hair)
    case Dog(hair) => println("processing dog, hair=" + hair)
    case s @ Sheep(hair) => {
      println("processing sheep, cutting hair...")
      //cut(hair)
      s.hair = None
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

但你不必使用var.这是您的代码段的更多功能版本.what这里只是返回SheepNone Hair切割后.

trait Animal
case class Cat(hair: Option[Hair]) extends Animal
case class Dog(hair: Option[Hair]) extends Animal
case class Sheep(hair: Option[Hair]) extends Animal

def what(animal: Animal): Animal =
  animal match {
    case Cat(hair) => {
      println("processing cat, hair=" + hair)
      animal
    }
    case Dog(hair) => {
      println("processing dog, hair=" + hair)
      animal
    }
    case Sheep(hair) => {
      println("processing sheep, cutting hair...")
      //cut(hair)
      Sheep(None)
    }
  }
}
Run Code Online (Sandbox Code Playgroud)