How can I pattern match on a range in Scala? - Stack Overflow

PHOTO EMBED

Fri Feb 25 2022 21:50:26 GMT+0000 (UTC)

Saved by @joel113 #scala

class Contains(r: Range) { def unapply(i: Int): Boolean = r contains i }

val C1 = new Contains(3 to 10)
val C2 = new Contains(20 to 30)

scala> 5 match { case C1() => println("C1"); case C2() => println("C2"); case _ => println("none") }
C1

scala> 23 match { case C1() => println("C1"); case C2() => println("C2"); case _ => println("none") }
C2

scala> 45 match { case C1() => println("C1"); case C2() => println("C2"); case _ => println("none") }
none
content_copyCOPY

https://stackoverflow.com/questions/3160888/how-can-i-pattern-match-on-a-range-in-scala