If you have a pattern matching (case) in Scala, for example:

foo match {
  case a: String => doSomething(a)
  case f: Float =>  doSomethingElse(f)
  case _ => ? // How does one determine what this was?
}

Is there a way to determine what type was actually caught in the catch-all?

有帮助吗?

解决方案 2

foo match {
  case a: String => doSomething(a)
  case f: Float =>  doSomethingElse(f)
  case x => println(x.getClass)
}

其他提示

case x => println(x.getClass)

Too easy :-)

Basically, you just need to bind the value in your catch-all statement to a name (x in this case), then you can use the standard getClass method to determine the type.

If you're trying to perform specific logic based on the type, you're probably doing it wrong. You could compose your match statements as partial functions if you need some 'default' cases that you don't want to define inline there. For instance:

scala> val defaultHandler: PartialFunction[Any, Unit] = {
     | case x: String => println("String: " + x)
     | }
defaultHandler: PartialFunction[Any,Unit] = <function1>

scala> val customHandler: PartialFunction[Any, Unit] = {
     | case x: Int => println("Int: " + x)
     | }
customHandler: PartialFunction[Any,Unit] = <function1>

scala> (customHandler orElse defaultHandler)("hey there")
String: hey there
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top