sealed trait Foo {
type T <: Option[Any]
val x : T
}
case class Bar(x : Option[Int]) extends Foo {
type T = Option[Int]
}
val baz : Foo = Bar(Some(42))
baz.x match {
case Some(a) => a
case None => 1337
}
This is the error message when attempting to pattern match:
:12: error: pattern type is incompatible with expected type;
found : None.type
required: baz.T
I believe this is due to type-erasure on type T.
I'm not sure why this fails, probably a limitation in the type inference. The following works:
(baz.x: Option[Any]) match {
case Some(a) => a
case None => 1337
}
In any case, asking for a subtype of Option
does not make sense. Better define the option's element type:
sealed trait Foo {
type A
def x: Option[A]
}
case class Bar(x : Option[Int]) extends Foo {
type A = Int
}
val baz : Foo = Bar(Some(42))
baz.x match {
case Some(a) => a
case None => 1337
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.