This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package matchers | |
object MatcherDemo { | |
abstract class Animal(val name: String) | |
case class Fish(override val name: String) extends Animal(name) | |
case class Mammal(override val name:String) extends Animal(name) | |
case class Reptile(override val name:String) extends Animal(name) | |
case class Bird(override val name:String) extends Animal(name) | |
val animals: List[Animal] = List(Mammal("Whale"),Fish("Tuna"), Mammal("Human"), | |
Bird("Owl"), Fish("Shark"), Reptile("Crocodile"), Fish("Shark")) | |
//filter all fish | |
val fishes = animals collect {case a: Fish => a } | |
/** | |
List(Fish(Tuna), Fish(Shark), Fish(Shark)) | |
**/ | |
//filter animals with letter 'o' in name | |
val animalsWithLetterO = animals.filter(a => a.name.toLowerCase().contains("o")) | |
/** | |
List(Bird(Owl), Reptile(Crocodile)) | |
**/ | |
val animalsGrouped = animals groupBy identity | |
/** | |
Map( | |
Fish(Shark) -> List(Fish(Shark), Fish(Shark)), | |
Bird(Owl) -> List(Bird(Owl)), | |
Mammal(Whale) -> List(Mammal(Whale)), | |
Fish(Tuna) -> List(Fish(Tuna)), | |
Mammal(Human) -> List(Mammal(Human)), | |
Reptile(Crocodile) -> List(Reptile(Crocodile)) | |
) | |
**/ | |
val animalsByType = animals.groupBy(a => a.getClass().getName()) | |
/** | |
Map( | |
matchers.MatcherDemo$Bird -> List(Bird(Owl)), | |
matchers.MatcherDemo$Mammal -> List(Mammal(Whale), Mammal(Human)), | |
matchers.MatcherDemo$Fish -> List(Fish(Tuna), Fish(Shark), Fish(Shark)), | |
matchers.MatcherDemo$Reptile -> List(Reptile(Crocodile)) | |
) | |
**/ | |
} |
No comments:
Post a Comment