两种模式匹配

Kev*_*ith 3 scala either

Scala中的Functional Programming,我正在尝试实现Either.map.

trait Either[+E, +A] {
    def map[B](f: A => B): Either[E, B] =  this match {
        case Either(x: E, y: A) => Right(f(y))
        case _ => Left()
    }
}
Run Code Online (Sandbox Code Playgroud)

编译中出现一个错误,其中包括.我没有展示它们,因为我似乎错过了实施的概念Either.

    Either.scala:3: error: value Either is not a case class constructor, 
nor does it have an unapply/unapplySeq method
                    case Either(x: E, y: A) => Right(f(y))
Run Code Online (Sandbox Code Playgroud)

请告知我实施它.

S.R*_*R.I 5

错误消息表明您不能Either用作案例类构造函数.IOW,Either相当于一个抽象类,因为您已将其编码为具有自己的可实现方法的特征.假设您有以下编码表示Either,Left并且Right:

sealed trait Either[+E, +A] {
    def map[B](f: A => B): Either[E, B] =  ???
}

// Left signifies error condition
// Right is something Right, along with its message.
case class Left[+E](err: E) extends Either[E,Nothing]
case class Right[+E](msg: E) extends Either[Nothing,E]
Run Code Online (Sandbox Code Playgroud)

您可以将map函数编写为:

def map[B](f: A => B): Either[E, B] = this match {
    case Right(v) => Right(f(v))
    case Left(e) => Left(e)
}
Run Code Online (Sandbox Code Playgroud)

在这里我简单地说,如果你遇到一些应该是正确值的东西,对它执行一些函数计算并完全按照它应该返回它 - a Right.既然Eithersealed trait(主要是为了方便),唯一的其他类型可以是Left我按原样返回的类型.了解更多Either