0

以下のコードは例外をスローしています:

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

この例外をキャッチして、マップ機能を次のアイテムに続行したいと思います。例外を無視して残りの関数を続行するには、より高次の関数を try/catch で囲みます: groupBy & mapValues ?

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

3 に答える 3

3

Stringで索引付けを行うことができますTry。は、以下の例に示すようにorTryを返します。次に、これらの値を照合して、残りの式を構成できます。これは練習問題として残しておきます。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 に答える