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

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

    I encountered the same problem and placing the class in a 'stable identifier' wasn't that practical. I found the next best thing was to have tidy 'else if' statements.

    Using this method:

    private def is[T <: AnyRef : Manifest](implicit cls: Class[_]) = 
        cls == manifest[T].runtimeClass
    

    I can write:

      implicit val arg = cls   
      if (is[ClassA]) ...
      else if (is[ClassB]) ...
      ...
      else throw new IllegalArgumentException("Unknown class: " + cls)
    

提交回复
热议问题