正如@Fatih麥茲說,這是一個Parital功能可按,這個定義的某些類型的某些值,用法:
List("hello", "test").foreach {
case "test" => println("received test")
case _ => println("received unknown message")
}
(0 to 20) collect {
case i if i % 2 == 0 => i
}
(0 to 20) map {
case i if i % 2 == 0 => i * i
case j => j
}
你也可以直接使用它,比如:
val f1: PartialFunction[Int, Unit] = {
case 1 => println("I am 1")
case t => println(s"I am $t")
}
f1(1)
> I am 1
f1(2)
> I am 2
否則容易實施例:
val f1: PartialFunction[Int, Int] = {
case i if i % 2 == 0 => i * i
}
val f2: PartialFunction[Int, Int] = {
case i if i % 2 != 0 => i+1
}
val f = f1 orElse f2
f(1)
> 2
(0 to 10) map f
> scala.collection.immutable.IndexedSeq[Int] = Vector(0, 2, 4, 4, 16, 6, 36, 8, 64, 10, 100)
andThen實施例:
val f1: PartialFunction[Int, Int] = {
case i if i % 2 == 0 => i * i
case j => j
}
val f2: PartialFunction[Int, Int] = {
case i if i % 2 != 0 => i * i
case j => j + 1
}
val f = f1 andThen f2
f(2)
res20: Int = 5
(0 to 10) map f
> scala.collection.immutable.IndexedSeq[Int] = Vector(1, 1, 5, 9, 17, 25, 37, 49, 65, 81, 101)
構成實施例:
val f1: PartialFunction[Int, Int] = {
case i if i % 2 == 0 => i * i
case j => j
}
val f2: PartialFunction[Int, Int] = {
case i if i % 2 != 0 => i * i
case j => j + 1
}
val f = f1 compose f2
f(2)
res18: Int = 3
(0 to 10) map f
res17: scala.collection.immutable.IndexedSeq[Int] = Vector(1, 1, 3, 9, 5, 25, 7, 49, 9, 81, 11)
文檔:
- https://twitter.github.io/scala_school/pattern-matching-and-functional-composition.html
- https://twitter.github.io/scala_school/pattern-matching-and-functional-composition.html
你能放下文檔鏈接呢?看起來它會對收到的消息進行模式匹配。 – Pavel