特征中的scala模式匹配

时间:2016-06-12 19:36:03

标签: scala types pattern-matching

sealed trait Option_40to49[+A] {
  def map[B](f: A => B): Option[B] = this match {
    case None => None
    case Some(x) => Some(f(x))
  }
}

我在eclipse中工作,它在下一个错误下划线为无:

pattern type is incompatible with expected type; found : None.type required: packageName.Option_40to49[A]

和Some(x)相似

constructor cannot be instantiated to expected type; found : Some[A(in class Some)] required: packageName.Option_40to49[A(in trait Option_40to49)]

为什么我有这个问题?如何解决?

1 个答案:

答案 0 :(得分:2)

在模式匹配中使用this,您指的是Option_40to49,但由于您尚未实现NoneSome,编译器不知道这是什么

这些的简单版本并不难以实现。请注意,您还需要将map的输出更改为Option_40to49

sealed trait Option_40to49[+A] {
  def map[B](f: A => B): Option_40to49[B] = this match {
    case None => None
    case Some(x) => Some(f(x))
  }
}

case class Some[A](x: A) extends Option_40to49[A]
case object None extends Option_40to49[Nothing]