我非常喜欢 Rumeshs 解决方案,但如果您更喜欢模式匹配样式:
def convert (list: List [String]): List [Either [String, Int]] = list match {
case Nil => Nil
case head :: tail => if (head.matches ("[0-9]+"))
Right (head.toInt) :: convert (tail) else
Left (head) +: convert (tail)
}
convert (List("3", "four", "55"))
// res304: List[scala.util.Either[String,Int]] = List(Right(3), Left(four), Right(55))
convert (List("3", "4", "55"))
// res305: List[scala.util.Either[String,Int]] = List(Right(3), Right(4), Right(55))
最后转成Seq很简单
convert (List("3", "4", "55")).toSeq
或者使用你自己的方法 +: ,但是它会返回一个 List,因为 List 是一个 Seq,但它会错过失败的 .toInt 调用。
我没有测试它 - 也许这个解决方案比 Try{} 方法更快,也可能更慢,可能取决于与 int 匹配失败的频率。
Rumesh 指出,list.map 是同时工作的,所以这里是他的方法的字符串意义上的模式匹配:
List("3", "four", "55") .map (ele =>
if (ele.matches ("[0-9]+")) Right (ele.toInt) else (Left(ele))).toSeq
// res307: scala.collection.immutable.Seq[Product with Serializable with scala.util.Either[String,Int]] = List(Right(3), Left(four), Right(55))
List("3", "4", "55") .map (ele =>
if (ele.matches ("[0-9]+")) Right (ele.toInt) else (Left(ele))).toSeq
// res308: scala.collection.immutable.Seq[Product with Serializable with scala.util.Either[String,Int]] = List(Right(3), Right(4), Right(55))