scala – 将任意列表转成列表的最佳方法?
发布时间:2020-12-16 09:42:36 所属栏目:安全 来源:网络整理
导读:我有一些如下所示的代码,其中有一个Eithers的列表,我想把它变成一个列表,特别是(在这种情况下),如果列表中有左列,那么我返回他们的列表的左边,否则我返回权利列表的权利。 val maybe: List[Either[String,Int]] = getMaybeval (strings,ints) = maybe.
我有一些如下所示的代码,其中有一个Eithers的列表,我想把它变成一个列表,特别是(在这种情况下),如果列表中有左列,那么我返回他们的列表的左边,否则我返回权利列表的权利。
val maybe: List[Either[String,Int]] = getMaybe val (strings,ints) = maybe.partition(_.isLeft) strings.map(_.left.get) match { case Nil => Right(ints.map(_.right.get)) case stringList => Left(stringList) } 打电话给我总是让我觉得我一定是错过了一些东西。 有没有更惯用的方法来做到这一点? 解决方法data.partition(_.isLeft) match { case (Nil,ints) => Right(for(Right(i) <- ints) yield i) case (strings,_) => Left(for(Left(s) <- strings) yield s) } 一次通过: data.partition(_.isLeft) match { case (Nil,ints) => Right(for(Right(i) <- ints.view) yield i) case (strings,_) => Left(for(Left(s) <- strings.view) yield s) } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |