我有一个总和特征,如下所示:
sealed trait Sum[+A, +B]
final case class Failure[A](value: A) extends Sum[A, Nothing]
final case class Success[B](value: B) extends Sum[Nothing, B]
当我尝试创建一个新变量时:
val s1: Sum[Int, Nothing] = Success(4)
我遇到以下错误:
Error:(5, 41) type mismatch;
found : Int(4)
required: Nothing
val s1: Sum[Int, Nothing] = Success(4)
为什么?
为什么这样做有效:
val s1: Sum[Int, Int] = Success(4)
答案 0 :(得分:4)
因为B
是第二个类型参数,而不是第一个:
val s1: Sum[Nothing, Int] = Success(4)