情况f:Int和case f @ Int之间的区别

时间:2017-11-23 09:47:07

标签: scala

case x:Intcase x @ Int之间有什么区别?在下面的示例中,为什么在case x@Int参数传递时不匹配Int

scala> def matchInt (x:Any) = x match {
     | case x:Int => println("got int"+x) //this matches with Int
     | case _ => println("no int "+x)
     | }
matchInt: (x: Any)Unit

scala> matchInt(1)
got int1

scala> matchInt("2")
no int 2

scala> def matchInt (x:Any) = x match {
     | case x @ Int => println("got int"+x) //this doesn't matches with Int
     | case _ => println("no int "+x)
     | }
matchInt: (x: Any)Unit

scala> matchInt("2")
no int 2

scala> matchInt(1)
no int 1

scala>

2 个答案:

答案 0 :(得分:2)

jobs表示“类型为Int的x”。 x:Int表示“x 类型为Int”。 在这种情况下,后者非常无用。

答案 1 :(得分:1)

我们使用x: Int进行类型模式匹配,有时您可能希望向模式添加变量。您可以使用以下常规语法执行此操作:variableName @ pattern

  1. 对于x: Int,您的模式匹配可以匹配x的类型。
  2. 对于variableName @ pattern,请查看我们匹配各种模式的示例:

    scala> case class Test(t1: String, t2: String)
    defined class Test
    
    scala> object Test2 extends App {
             |   def matchType(x: Any): String = x match {
             |     case y @ List(1, _*) => s"$y"   // works; prints the list
             |     case y @ Some(_) => s"$y"   // works, returns "Some(Hiii)"
             |     case y @ Test("t1", "t2") => s"$y"  // works, returns "Test(t1,t2)"
             |   }
             | }
    defined object Test2
    
    scala>  Test2.matchType(List(1,2,3))
    res2: String = List(1, 2, 3)
    
    scala> Test2.matchType(Some("Hiii"))
    res3: String = Some(Hiii)
    
    scala> Test2.matchType(Test("t1","t2"))
    res4: String = Test(t1,t2)
    
相关问题