Created
January 29, 2019 20:14
-
-
Save gmaslowski/a683466ebc7d91f71fa2d4e72990b6a5 to your computer and use it in GitHub Desktop.
Scala Samples - Extractors vs Case Classes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.gmaslowski.scala.samples.extractor | |
object ScalaExtractorSample extends App { | |
val casePeople = List( | |
Case.Person("John", "Doe"), | |
Case.Person("Jane", "Doe"), | |
Case.Person("Jimmy", "Doe"), | |
Case.Person("Bobby", "Doe"), | |
Case.Person("Jimmy", "Known"), | |
Case.Person("Clair", "Known") | |
) | |
val byHandPeople = List( | |
ByHand.Person("John", "Doe"), | |
ByHand.Person("Jane", "Doe"), | |
ByHand.Person("Jimmy", "Doe"), | |
ByHand.Person("Bobby", "Doe"), | |
ByHand.Person("Jimmy", "Known"), | |
ByHand.Person("Clair", "Known") | |
) | |
casePeople | |
.map { | |
case p @ Case.Person(_, "Doe") => (p, "Lastname is Doe.") | |
case p @ Case.Person("Jimmy", _) => (p, "Firstname is Jimmy.") | |
case p @ Case.Person(_, _) => (p, "Not important.") | |
} | |
.foreach(println) | |
byHandPeople | |
.map { | |
case p @ ByHand.Person(_, "Doe") => (p, "Lastname is Doe.") | |
case p @ ByHand.Person("Jimmy", _) => (p, "Firstname is Jimmy.") | |
case p @ ByHand.Person(_, _) => (p, "Not important.") | |
} | |
.foreach(println) | |
} | |
object Case { | |
case class Person(firstname: String, lastname: String) | |
} | |
object ByHand { | |
class Person(val firstname: String, val lastname: String){ | |
override def toString: String = s"ByHandPerson($firstname, $lastname)" | |
} | |
object Person { | |
def apply(firstname: String, lastname: String) = new Person(firstname, lastname) | |
def unapply(person: Person): Option[(String, String)] = Some((person.firstname, person.lastname)) | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment