How can I match classes in a Scala “match” statement?

前端 未结 4 1953
孤独总比滥情好
孤独总比滥情好 2021-01-01 14:43

How can I use a \"match\" statement to identify the value of a class variable? The following is invalid, and I can\'t find an acceptable variant -- other than if ... else i

4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-01 15:15

    You can match on class values if you create a stable identifier (ie. a val) for them,

    scala> val c: Class[_] = classOf[Int]
    c: Class[_] = int
    
    scala> val ClassOfInt = classOf[Int]
    ClassOfInt: java.lang.Class[Int] = int
    
    scala> val ClassOfFloat = classOf[Float]
    ClassOfFloat: java.lang.Class[Float] = float
    
    scala> val what = c match {
         |     case ClassOfInt => "int!"
         |     case ClassOfFloat => "float!"
         | }
    what: String = int!
    

    Note that you can't match on type (ie. Class[Int]) because erasure means that the different type instantiations of Class[T] are indistinguishable at runtime ... hence the warning below

    scala> val what = c match {
         |     case _: Class[Int] => "int!"
         |     case _: Class[Float] => "float!"
         | }
    warning: there were 2 unchecked warnings; re-run with -unchecked for details
    what: java.lang.String = int!
    

提交回复
热议问题