Scala:无法解析函数

时间:2017-02-28 05:05:37

标签: scala

我想再次重新实现scala left / right /。这是我的代码:

case class Left[+E](get: E) extends Either[E, Nothing]

case class Right[+A](get: A) extends Either[Nothing, A]

 sealed trait Either[+E, +A] {

  def orElse[EE >: E, B](b: => Either[EE, B]): Either[EE, B]
    this match {
      case Left(_) => b              // error here
      case Right(a) => Right(a)
    }

}

我不知道在case Left(_) => b

我遇到了什么错误
  

无法解析符号b

但是这个方法不会抛出错误:

def orElse[EE >: E, AA >: A](b: => Either[EE, AA]): Either[EE, AA] =
  this match {
    case Left(_) => b
    case Right(a) => Right(a)
  }

请告诉我。

1 个答案:

答案 0 :(得分:2)

正如@jwvh在评论中所述,您在定义中缺少=

def orElse[EE >: E, B](b: => Either[EE, B]): Either[EE, B] = ...

如果没有=,编译器会看到一个抽象的orElse方法和一些随机初始化代码,而不是一个实现的方法。有时使用大括号有助于解决此类案件

但是,在添加=之后,您会收到类型错误,因为B必须与A中的Either相关联,否则this将与传递的值不匹配(类似于你怎么得到AA),留下你:

def orElse[EE >: E, B >: A](b: => Either[EE, B]): Either[EE, B] = ...

B替换为AA并获得原始工作示例

相关问题