간단한 예제를 작성하여 패턴 일치를 이해하려고합니다. 여기있다 :왜 scala match.error가 던져 집니까?
def main(args: Array[String]) = {
val tsm = new Test[Number]
tsm.foo(tsm.Val(10))
}
class Test[T <: Any] {
def foo(t: Any): Unit = {
val f: PartialFunction[Any, Unit] = (_: Any) match {
case Val(s) => println("Val" + s)
case Sup(l) => println("Sup" + l)
}
f()
}
class Val(val t: T)
class Sup(val l: Number)
object Val{
def apply(t: T): Val = new Val(t)
def unapply(arg: Val): Option[T] = Some(arg.t)
}
object Sup{
def unapply(arg: Sup): Option[Number] = Some(arg.l)
}
}
그러나 코드 예외 :
Exception in thread "main" scala.MatchError:() (of class scala.runtime.BoxedUnit)
at scala.PartialFunction$$anon$1.apply(PartialFunction.scala:253)
at scala.PartialFunction$$anon$1.apply(PartialFunction.scala:251)
at com.test.Test$$anonfun$1.applyOrElse(Test.scala:7)
at scala.runtime.AbstractPartialFunction.apply(AbstractPartialFunction.scala:36)
at com.test.Test.foo(Test.scala:11)
at com.test.App$.main(App.scala:6)
at com.test.App.main(App.scala)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
내가 확실히 이해하지. 나는 유형 Val(10)
의 객체를 만들고이를 foo
으로 전달했습니다. 나는 그것이 Val10
를 인쇄 할 것으로 예상했다.
Arghh ... 왜 컴파일 시간에 발견되지 않습니까? 그것은 이상하게 보입니다 ... – user3663882
@ user3663882'-deprecation'으로'scalac'을 실행하면, 경고 메시지가 나타납니다 : warning :'inserted()에 의한 인수 목록의 적용이 더 이상 사용되지 않습니다 : 이것은 가능하지 않습니다 당신이 원하는 것입니다. 서명 : Function1.apply (v1 : T1) : R 주어진 인수 : 적응 후 : Function1 (() : Unit) f()' –
Alec