Question

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?

Était-ce utile?

La solution 2

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

Autres conseils

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
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top