3 ms·
An example of Scala's pattern matching: case class Person(name: String, age: Int) // a collection of 3 people val c1 = Vector(Person("A", 5), Pers
by dxxvi 7y ago
An example of Scala's pattern matching:
case class Person(name: String, age: Int)
// a collection of 3 people
val c1 = Vector(Person("A", 5), Person("B", 6), Person("C", 4))
// now I want a collection of people who have age > 4 and then their ages are doubled
val c2 = c1 collect { case Person(name, age) if age > 4 => Person(name, age*2) }
How do you write it in Java 14?
Want something lazy like Java streams? It's LazyList in Scala 2.13 and Stream in Scala < 2.13.
- sorokod 7y agoIn Kotlin data class Person (val name: String, val age: Int) val c1 = listOf(Person("A", 5), Person("B", 6), Person("C", 4)) val c2 = c1.filter{ it.age > 4 }.map{ it.copy(age = it.age*2) }
- dxxvi 7y agoKotlin and Java don't have a powerful pattern matching like Scala. Maybe that's why they don't have `collect` for filter + map. However I'm learning kotlin now because my employer doesn't allow me to use Scala