1

実際、私は自分のコードを html パーサーで使用しています。しかし、ここではテスト用に書き直します。

def parse: Int = {
  var texts = Array("a.b.c.d.1321,123.f")
  for (text <- texts) {
    var lines = text.split("\\.")
    return try { lines(4).replaceAll("[^0-9]", "").toInt } catch { case _ => 0 }
  }
  0
}

Call parse、私はこの例外を受け取りました:

java.lang.VerifyError: (class: $anonfun$parse$1, method: apply signature: (Ljava/lang/String;)Lscala/runtime/Nothing$;) Inconsistent stack height 0 != 3
        at .parse(<console>:10)
        at .<init>(<console>:10)
        at .<clinit>(<console>)
        at .<init>(<console>:11)
        at .<clinit>(<console>)
        at $print(<console>)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:601)
        at scala.tools.nsc.interpreter.IMain$ReadEvalPrint.call(IMain.scala:704)
        at scala.tools.nsc.interpreter.IMain$Request$$anonfun$14.apply(IMain.scala:920)
        at scala.tools.nsc.interpreter.Line$$anonfun$1.apply$mcV$sp(Line.scala:43)
        at scala.tools.nsc.io.package$$anon$2.run(package.scala:25)
        at java.lang.Thread.run(Thread.java:722)

私の質問は、なぜコードがその例外を発生させるのですか?

編集済み

コーディング スタイルについては言及せず、例外に注目してください。コードを正常にコンパイルできるためです。

編集済み

結果を少し変更します。

def parse: Int = {
  var texts = Array("a.b.c.d.1321,123.f")
  for (text <- texts) {
    var lines = text.split("\\.")
    return try { lines(4).replaceAll("[^0-9]", "").toInt } catch { case _ => -1 }
  }
  0
}

forループを使用しない場合は問題ありません。

def parse: Int = {
  var text = "a.b.c.d.1321,123.f"
  var lines = text.split("\\.")
  return try { lines(4).replaceAll("[^0-9]", "").toInt } catch { case _ => -1 }
}

しかし、私はまだ最初のケースについて混乱しています。

4

1 に答える 1

4

tryブロック全体の結果を返しているためと思われます。returnブロック内を移動しても問題ありません。

try { return lines(4).replaceAll("[^0-9]", "").toInt } catch { case _ => return 0 }

ループtry内でブロックを返すことに関連するコンパイラのバグのようです。forこれが正常に機能することに注意してください。

def parse: Int = {
  return try { 1 } catch { case _ => 0 }
  0
}

これは失敗しますが:

def parse: Int = {
  for (x <- List(1))
    return try { 1 } catch { case _ => 0 }
  0
}
于 2012-01-17T04:15:06.073 に答える