0

下面的代码抛出异常:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at line
(s(0).toString,s(0).toString)

我想捕获这个异常,然后将 map 函数继续到下一个项目。如何围绕高阶函数围绕 try / catch 以忽略任何异常并继续使用其余函数:groupBy 和 mapValues ?

println(toIterate.toList.map(s => (s(0).toString,s(0).toString))
    .groupBy(_._1)
    .mapValues(_.map(_._2)))
4

3 回答 3

3

您可以StringTry. 将Try返回SuccessFailure如下例所示。然后,您可以匹配这些值以组成表达式的其余部分。我会把它留给你作为练习。

scala> val f = "foo"
f: String = foo

scala> List(0,1,2,3,4).map(xs => Try(f(xs)))
res0: List[scala.util.Try[Char]] = List(Success(f), Success(o), Success(o), Failure(java.lang.StringIndexOutOfBoundsException: String index out of range: 3), Failure(java.lang.StringIndexOutOfBoundsException: String index out of range: 4))
于 2013-08-30T22:54:40.850 回答
0

如果您的目标是过滤掉会发生异常的项目,您应该使用filter

println(toIterate.toList
    .filter(_.length > 0)
    .map(s => (s(0).toString,s(0).toString))
    .groupBy(_._1)
    .mapValues(_.map(_._2)))
于 2013-08-30T22:41:24.947 回答
0

如果您的问题是关于 try and catch 的语法,谷歌搜索“try catch scala”将显示一些选项。但我认为更现实的答案是在模式映射时使用“if”条件(参考这篇优秀的文章)以及“Collect”

http://danielwestheide.com/blog/2012/12/12/the-neophytes-guide-to-scala-part-4-pattern-matching-anonymous-functions.html#comment-975636567

像这样的东西(对不起,你可能不得不玩语法)

println(toIterate.toList.collect(case(s) if s.len>0).map( s => (s(0).toString,s(0).toString)) .groupBy(_._1) .mapValues(_.map(_._2)))
于 2013-08-30T22:49:12.080 回答