1

私はいくつかの演習を行っていましたが、tuple2のマッチングについて次の動作に気づきました。これには特別な理由がありますか?

 def test(x: Any): Unit= x match{
  case i: Int => println("int")
  case b: Boolean => println("bool")
  case ti: (_, Int) => println("tuple2 with int")
  case tb: (_, Boolean)=> println("tuple2 with boolean")
  case _ => println("other")
  }                                                

test(false) //prints bool
test(3) ///prints int
test((1,3)) //prints tuple with int
test((1,true)) //prints tuple with int 

tiとtbのケースを交換すると、(1,3)はtuple2をブール値で出力します。ここで型キャストが行われていると思いますが、その理由はわかりません。

誰かが私に簡単な説明をしてもらえますか?ありがとう

4

3 に答える 3

4

型消去。実行時にどのタイプが内部にあるかはわかりませんTuple。正常にコンパイルされますが、警告が表示されます。:pasteこれは、REPLのモードで実行するとどうなるかです。

scala> :paste
// Entering paste mode (ctrl-D to finish)

def test(x: Any): Unit= x match{
  case i: Int => println("int")
  case b: Boolean => println("bool")
  case ti: (_, Int) => println("tuple2 with int")
  case tb: (_, Boolean)=> println("tuple2 with boolean")
  case _ => println("other")
  }                                                

// Exiting paste mode, now interpreting.

<console>:10: warning: non-variable type argument Int in type pattern (_, Int) is unchecked since it is eliminated by erasure
         case ti: (_, Int) => println("tuple2 with int")
                  ^
<console>:11: warning: non-variable type argument Boolean in type pattern (_, Boolean) is unchecked since it is eliminated by erasure
         case tb: (_, Boolean)=> println("tuple2 with boolean")
                  ^
<console>:11: warning: unreachable code
         case tb: (_, Boolean)=> println("tuple2 with boolean")
                                        ^
test: (x: Any)Unit

最後の警告に注意してください。型消去のおかげで、はすべてに一致する(_, Boolean)ため、到達不能であると表示されます。(_, Int)Tuple2

于 2013-01-28T01:49:00.820 に答える
0
def test(x: Any) {
x match {
  case xi: Int => println("int [" + xi + "]")
  case yb: Boolean => println("boolean [" + yb + "]")
  case (x, y @ (y1: Int)) => println("[" + x + ", int(" + y + ")]")
  case (x, y @ (y1: Boolean)) => println("[" + x + ", boolean(" + y + ")]")
  case _ => println("anything else")
}

}

test(1);
test(true);
test("hello", 1);
test("hello", false);

このように機能するようです。ただし、大文字と小文字(x、y @ Int)は、準拠していても機能しません。

于 2013-01-28T04:35:00.507 に答える
0

これを試すことができます。コードに最小限の変更を加えるだけで問題なく動作します。解凍して入力することで、関数は正常に機能します。

def test: Any => Unit = _ match{
  case i: Int => println("int")
  case b: Boolean => println("bool")
  case (x:Any, y: Boolean)=> println("tuple2 with boolean")
  case (x:Any, y: Int) => println("tuple2 with int")
  case _ => println("other")
}
于 2013-01-28T06:10:27.037 に答える