Passing Scala Class as parameter?

前端 未结 3 567
故里飘歌
故里飘歌 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:07

    Well, to your original question: Yes, you can pass Scala Class as an argument. As Class is a type constructor, it needs a concrete type to make a type to be used in argument. You can use the wildcard existential type Class[_] as you have done.

    def sample(c: Class[_]) = println("Get a class")
    sample(classOf[Int])
    

    However, if you want to check whether an object is of certain type, I recommend you to use =:=, in combination with default parameter

    def checkType[T](obj: T)(implict ev: T =:= Int = null) =
      if (ev == null) "get other"
      else "get int"
    checkType(123) // get int
    checkType("123") // get other
    

提交回复
热议问题