Passing Scala Class as parameter?

2020-05-19 06:43发布

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 type in the parameter be Class or Class[_]?)

The reason I'm passing a Class type is to check whether an object belongs to a particular type or not. At the moment, as a workaround, I'm passing a sample object to the method and comparing the two object's .getClass result. I hardly think this is ideal though and I'm sure there's a clearly defined way of passing Types in Scala.

标签: scala
3条回答
兄弟一词,经得起流年.
2楼-- · 2020-05-19 07:03

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

查看更多
够拽才男人
3楼-- · 2020-05-19 07:09

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
查看更多
家丑人穷心不美
4楼-- · 2020-05-19 07:16

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
查看更多
登录 后发表回答