Passing Scala Class as parameter?

前端 未结 3 566
故里飘歌
故里飘歌 2021-02-01 19:45

I\'m looking to pass a Class as a parameter to a Scala function like so:

def sampleFunc (c : Class) : List[Any]  

(Side question: should the ty

3条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-01 20:00

    Yes. In general case it's ClassTag/TypeTag - see Mirrors and Reflection

    import scala.reflect._
    def runtimeClass[T: ClassTag] = classTag[T].runtimeClass
    
    scala> runtimeClass[String]
    res2: Class[_] = class java.lang.String
    

    If you really need only to check compile-time (formal) type equality

    scala> implicitly[String =:= Double]
    :14: error: Cannot prove that String =:= Double.
              implicitly[String =:= Double]
                        ^
    

    If you really need to check only type of object:

     scala> "aa".isInstanceOf[String]
     res4: Boolean = true
    

提交回复
热议问题