Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pattern match a List of case classes in Scala

Say I have a List of case classes that I want to pattern match and return true or false if there is a type. For example.,

case class TypeA(one: String, two: Int, three: String)

val list = List(TypeA, TypeA, TypeA)

I want to now match against the list of types and see if TypeA contains a certain value for one of its parameter (say the first parameter). What I have is the following:

def isAvailableInTypeA(list: List[TypeA], checkStr: String) = {
  !(list.dropWhile(_.one != checkStr).isEmpty))
}

Is there a better more readable suggestion for what I want to achieve?

like image 533
joesan Avatar asked Dec 14 '22 20:12

joesan


1 Answers

If you want to check whether the predicate holds for an element of the list, use .exists.

scala> val l = List(TypeA("a",2,"b"), TypeA("b",2,"b"))
l: List[TypeA] = List(TypeA(a,2,b), TypeA(b,2,b))

scala> l.exists(_.one == "a")
res0: Boolean = true

scala> l.exists(_.one == "c")
res1: Boolean = false
like image 185
Marth Avatar answered Jan 06 '23 21:01

Marth