Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Filtering collections on Scala
// Cat class definition
// I'm not kidding, nothing else is needed, but this is other topic
class Cat(val age: Int)
// With type inference and concise functional constructions
val a = Array(new Cat(age=1),new Cat(age=2))
// Filtering 1 year old cats
val age_1 = a.filter(_.age == 1)
print age_1 //Array[Cat] = Array(Cat@7596e2a5) (Needs toString method, but you get the point)
// Withot type inference and explicit functional constructions
val a:Array[Cat] = Array(new Cat(age=1),new Cat(age=2))
// Filtering 2 year old cats
val age_2 = a.filter((cat) => cat.age == 2)
print age_2 //Array[Cat] = Array(Cat@4f9faf3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment