Scala向右映射或向左返回 [英] Scala Either map Right or return Left

查看:117
本文介绍了Scala向右映射或向左返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以以与Option类似的方式处理Either?在Option中,我有一个getOrElse函数,在Either中,我想返回Left或处理Right.我正在寻找没有任何样板的最快方法:

Is it possible to handle Either in similar way to Option? In Option, I have a getOrElse function, in Either I want to return Left or process Right. I'm looking for the fastest way of doing this without any boilerplate like:

val myEither:Either[String, Object] = Right(new Object())
myEither match {
    case Left(leftValue) => value
    case Right(righValue) => 
        "Success"
}

推荐答案

在Scala 2.12中,

In Scala 2.12,

任何一个都是右偏的,这表示右假定为默认情况下进行操作.如果为Left,则诸如map,flatMap之类的操作将返回Left值不变

所以你可以做

myEither.map(_ => "Success").merge

(如果您发现它比fold更具可读性).

if you find it more readable than fold.

这篇关于Scala向右映射或向左返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆