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

前端 未结 4 1952
孤独总比滥情好
孤独总比滥情好 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:01

    The verbose case comparison works:

    val what = c match {
      case q if q == classOf[Int] => "int!"
      case q if q == classOf[Float] => "float!"
    }
    

    Of course, being a lower-case identifier, classOf should not work directly in a case statement anyway. However, neither does an escaped

    case `classOf`[Int]
    

    work in this case, so you’ll have to go with the if-guard.

提交回复
热议问题