Passing Scala Class as parameter?

前端 未结 3 565
故里飘歌
故里飘歌 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]
    <console>: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
    
    0 讨论(0)
  • 2021-02-01 20:01

    In Scala, if you need to deal with classes, there is probably a different way to approach the problem.

    So I'm not claiming to resolve the title of the question, but the specific need that you post. To check if a specific object is of a specific type, the typical approach in Scala is the use of pattern matching. Unless I'm missing something, this should work

    def checkType(obj: Any) = obj match {
      case y: Int => "get int"
      case _ => "Other"
    }
    

    See http://docs.scala-lang.org/tutorials/tour/pattern-matching.html

    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题