Scala中带有类对象的Case Switch语句

Scala中带有类对象的Case Switch语句,scala,reflection,pattern-matching,type-erasure,Scala,Reflection,Pattern Matching,Type Erasure,我试图在Scala中使用case switch语句来检查Javaclass对象所代表的类/类型。我不能传递实际的对象,但是我可以得到类,并且我需要根据该类对象执行不同的逻辑。比如说, def foo(classObj: Class[_]): Any = { classObj match { case map: Map[String, String] => doMapThings() case str: String => doStringThings() }

我试图在Scala中使用case switch语句来检查Java
class
对象所代表的类/类型。我不能传递实际的对象,但是我可以得到类,并且我需要根据该类对象执行不同的逻辑。比如说,

def foo(classObj: Class[_]): Any = {
  classObj match {
    case map: Map[String, String] => doMapThings()
    case str: String => doStringThings()
  }
}

但是,这实际上不起作用,因为case语句正在查看类的类型,即Class,并且永远不会是Map或String。我如何获得
classObj
表示的类型/类,并与其匹配?

为什么不简单地执行以下明显的操作:

def foo(c: Class[_]): Unit = {
  if (c == classOf[Map[_, _]]) println("do Map things") 
  else if (c == classOf[String]) println("do string things") 
  else println("do sth. else") }
}
您可以使用
将其重写为
匹配
-表达式,如果
-保护:

c match {
  case x if x == classOf[Map[_, _]] => ... 
  ...
}

但这似乎并没有更短或更清晰。另请注意:由于类型擦除,您无法在运行时区分
Map[Int,Double]
Map[String,String]

为什么不简单地执行显而易见的操作:

def foo(c: Class[_]): Unit = {
  if (c == classOf[Map[_, _]]) println("do Map things") 
  else if (c == classOf[String]) println("do string things") 
  else println("do sth. else") }
}
您可以使用
将其重写为
匹配
-表达式,如果
-保护:

c match {
  case x if x == classOf[Map[_, _]] => ... 
  ...
}

但这似乎并没有更短或更清晰。另请注意:由于类型擦除,您无法在运行时区分
Map[Int,Double]
Map[String,String]

您能解释一下上下文吗?传递一个类对象并返回
Any
感觉像是在对抗类型系统,而不是使用它。你为什么不能传递这个物体?你能解释一下它的上下文吗?传递一个类对象并返回
Any
感觉像是在对抗类型系统,而不是使用它。你为什么不能通过这个物体?