這是不推薦的(通常爲案例),但如果你真的需要它,使用PartialFuncion
明顯的一個?::
sealed trait Trait
case object A extends Trait
case object B extends Trait
scala> def f(x: Trait) = x match {
| case A => println("A")
| }
<console>:13: warning: match may not be exhaustive.
It would fail on the following input: B
def f(x: Trait) = x match {
^
f: (x: Trait)Unit
scala> val f: PartialFunction[Trait, Unit] = {
| case A => println("A")
| }
f: PartialFunction[Trait,Unit] = <function1>
scala> f(A)
A
scala> f(B)
scala.MatchError: B (of class B$)
at scala.PartialFunction$$anon$1.apply(PartialFunction.scala:254)
at scala.PartialFunction$$anon$1.apply(PartialFunction.scala:252)
at $anonfun$1.applyOrElse(<console>:14)
at $anonfun$1.applyOrElse(<console>:13)
at scala.runtime.AbstractPartialFunction.apply(AbstractPartialFunction.scala:34)
... 29 elided
的disadvant部分功能的年齡是它們會產生運行時異常的風險。但它們比@unchecked
方法更安全(應該在極端情況下使用) - 至少用戶可以從類型本身中看到潛在的異常。
在你的情況我建議你使用Option
和獨立的邏輯從效果:
def f(x: Trait) = x match {
case A => Some("A")
case _ => None
}
def effect(x: Option[String]) = x.foreach(println) //you can use getOrElse(throw RuntimeException) here
def run(x: Trait) = effect(f(x))
scala> run(A)
A
scala> run(B)
規範問題有一個非常具體的問題和答案。這個問題更一般,不應該被認爲是重複的。如果有的話,鏈接的問題需要編輯。 – noah