1

I want to a pattern is matching or not.

I end up writing a horrid piece of code like this

val isMatch = something match { 
    case Some(Complex(Pattern(matching) :: Nil)) => true
    case _ => false
}

This looks to me exactly like doing this

val isConditionTrue = if (someCondition) {
  true 
} else { 
  false 
}

Which is an eye sore and can be reduced of course to this

val isConditionTrue = someCondition

Or simply

someCondition

But I couldn't find a way (perhaps I'm missing something silly) to do that with a pattern matching (again, not talking about Regex here, just good old Scala pattern matching

Is there something to do here with a Partial Function / isDefinedAt etc? Is there any utility method to check e.g. something like

isPatternMatching(object, Pattern)
Eran Medan
  • 44,555
  • 61
  • 184
  • 276

1 Answers1

2

There's an answer where @extempore complains that no one ever offers this as an answer:

scala> import PartialFunction._
import PartialFunction._

scala> cond(Some(1)) { case Some(i) if i > 0 => true }
res0: Boolean = true

Update:

It was actually easy to find, because it's his top-rated answer.

https://stackoverflow.com/a/4442273/1296806

This was the source for the "impressively obscure" hoodie in the Scala store.

Community
  • 1
  • 1
som-snytt
  • 39,429
  • 2
  • 47
  • 129