【发布时间】:2017-01-13 20:02:23
【问题描述】:
如何重写以下内容以使其更“Scala 方式”或仅使用一个匹配项?
case class Foo(bar: Any)
val fooOpt = Some(Foo("bar as String"))
def isValid(p: Any) = p match {
case _ @ (_: String | _: Int) => true
case _ => false
}
//Is it possible to check for the type of bar directly in this if statement?
fooOpt match {
case Some(f) if isValid(f.bar) => doSomething
case _ => doSomethingElse
}
另一种方法是使用 isInstanceOf。
fooOpt match {
case Some(f) if f.bar.isInstanceOf[String] => doSomething
case Some(f) if f.bar.isInstanceOf[Int] => doSomething //could also rewrite to use just one case
case _ => doSomethingElse
}
还有其他方法吗?
【问题讨论】:
标签: scala pattern-matching scala-option