0
votes

I'm trying to use a case switch statement in Scala to check what class/type a Java Class object represents. I can't pass the actual object, but I can get the class and I need to perform different logic depending on that class object. For example,

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

However, this doesn't really work because the case statement is looking at the type of Class, which is Class, and will never be Map or String. How can I get the type/class that classObj represents and match on that instead?

1
Can you explain the context of this? Passing a class object and returning Any feels like working against the type system rather than with it. Why can't you pass the object? - Tim

1 Answers

3
votes

Why not simply do the obvious:

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") }
}

You could rewrite it as a match-expression using if-guards:

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

but this doesn't seem any shorter or clearer. Also note: you can't tell a Map[Int, Double] and a Map[String, String] apart at runtime because of the type erasure.