KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
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 } } } The questions are: 1) When pattern matching succeeds with a Sheep, how can I access it's hair and change it? It complained about reassignment to val, and I have then placed var in the constructor but still... 2) One more way I can think of is to assign the entire matched value to a variable, is there any way to bind a value matched by some case class constructor pattern to a variable? (I know that I could probably pattern match on something like s: Sheep and then call s.changeHairTo(None) but that is the least preferrable way).
Tags (comma-separated)
Save Edits
Cancel