Last active
March 15, 2021 06:17
-
-
Save linasm/003eec9eacc641167227193f5879bbd9 to your computer and use it in GitHub Desktop.
Output of live coding session "Scala pattern matching: apply the unapply"
This file contains 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
import java.time.{LocalDate, LocalDateTime, LocalTime} | |
/*case */class FullName(val first: String, val last: String) | |
object FullName { | |
def apply(first: String, last: String): FullName = | |
new FullName(first, last) | |
def unapply(full: FullName): Some[(String, String)] = | |
Some((full.first, full.last)) | |
} | |
val me = FullName("Linas", "Medžiūnas") | |
val FullName(meFirst, meLast) = me | |
object DateTime { | |
def unapply(dt: LocalDateTime): Some[(LocalDate, LocalTime)] = | |
Some((dt.toLocalDate, dt.toLocalTime)) | |
} | |
object DateTimeSeq { | |
def unapplySeq(dt: LocalDateTime): Some[Seq[Int]] = | |
Some(Seq( | |
dt.getYear, dt.getMonthValue, dt.getDayOfMonth, | |
dt.getHour, dt.getMinute, dt.getSecond)) | |
} | |
object Date { | |
def unapply(d: LocalDate): Some[(Int, Int, Int)] = | |
Some((d.getYear, d.getMonthValue, d.getDayOfMonth)) | |
} | |
object Time { | |
def unapply(t: LocalTime): Some[(Int, Int, Int)] = | |
Some((t.getHour, t.getMinute, t.getSecond)) | |
} | |
object AM { | |
def unapply(t: LocalTime): Option[(Int, Int, Int)] = | |
t match { | |
case Time(h, m, s) if h < 12 => Some((h, m, s)) | |
case _ => None | |
} | |
} | |
object PM { | |
def unapply(t: LocalTime): Option[(Int, Int, Int)] = | |
t match { | |
case Time(12, m, s) => Some(12, m, s) | |
case Time(h, m, s) if h > 12 => Some(h - 12, m, s) | |
case _ => None | |
} | |
} | |
val now = LocalDateTime.now | |
val dt @ DateTime(date @ Date(y, m, d), time @ Time(h, mm, s)) = now | |
val DateTimeSeq(y2, m2, d2, h2, _*) = now | |
Seq(LocalTime.now) map { | |
case t @ AM(h, m, _) => f"$h%2d:$m%02d AM ($t precisely)" | |
case t @ PM(h, m, _) => f"$h%2d:$m%02d PM ($t precisely)" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment