Manu Chadha
Manu Chadha

Reputation: 16729

case insensitive pattern match in Scala

I want to do pattern matching in Scala but it should be case insensitive. Is there a way I can write the code without using separate 'case' clauses for lower and upper cases

//person class with first name and last name
case class Person (var fn: String, val ln: String) {
  val name = fn
  val lastName = ln
}

//two instances. Same last name but cases are different
val a2 = Person("Andy","Cale")
val a3 = Person("Andy","cale")

def isCale(person:Person) {
person match {
//I want that this case should be case insensitive
  case Person(_,"Cale") => println("last-name Cale")
  case _ => println("not Cale")
}
}
isCale(a2) 
lastname Cale

//I want this to also match 
isCale(a3)
not Cale

One alternative is to extract the last name and compare as follows but I am interested in finding if there is a way to do this in case itself.

def isCale(a2:A2) {
  val s = a2.ln

  s.toLowerCase match {
  case "cale" => println("last-name Cale")
  case _ => println("not Cale")
}

Upvotes: 4

Views: 2347

Answers (2)

som-snytt
som-snytt

Reputation: 39577

You can use an extractor:

scala> val r = "(?i:it.*ov)".r
r: scala.util.matching.Regex = (?i:it.*ov)

scala> case class Person(firstName: String, lastName: String)
defined class Person

scala> val ps = Person("Fred", "Itchikov") :: Person("Yuval", "Itzchakov") :: Nil
ps: List[Person] = List(Person(Fred,Itchikov), Person(Yuval,Itzchakov))

scala> ps collect { case Person(_, n @ r()) => n }
res0: List[String] = List(Itchikov, Itzchakov)

Upvotes: 2

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149518

You can use a guard:

def main(args: Array[String]): Unit = {
  case class Person(firstName: String, lastName: String)

  val p = Person("Yuval", "Itzchakov")
  p match {
    case Person(_, lastName) if lastName.equalsIgnoreCase("itzchakov") =>
      println(s"Last name is: $lastName")
    case _ => println("Not itzchakov")
  }
}

Side note - case class parameters will be attached as vals on the declared class, there's no need for the additional assignment and no need for the val/var definition on the constructor.

Upvotes: 4

Related Questions