سؤال

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