Вопрос

This code:

trait Base[+K <: Option[Int]] {
  val a: K = None
}

class GuaranteedA extends Base[Some[Int]] {
  override val a = Some(1)
}

produces an error:

<console>:8: error: type mismatch;
 found   : None.type
 required: K
             val a: K = None

But why? The type constraint in K says K must be a subtype of Option[Int] which None is, even when I try to val a: K = Some(0) in Base, the same error is produced.

I'm very confused of this behavior and have no idea why this happens, maybe you can help me?

Это было полезно?

Решение

trait Base[K <: Option[Int]] just says that: There is a type K which is subtype of Option[Int]. Your second part GaranteedA shows exactly why your Base definition cannot pretend that None is a subtype of K—imagine that you did not override val a. You would end up having value None cast to a Some.

Just because K is a subtype of Option[Int] and None is a subtype of Option[Int], does not guarantee that None is a subtype of K.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top