Decomat 0.0.2 is out. Decomat is a library that al...
# feed
a
Decomat 0.0.2 is out. Decomat is a library that allows you to do deep-nested Scala-style pattern matching in Kotlin. Version 0.0.2 allows you to create custom patterns similar to Scala's unapply function:
Copy code
// Scala Style Unapply function:
sealed trait Name
case class SimpleName(first: String, last: String) extends Name
case class FullName(first: String, middle: String, last: String) extends Name

object FirstLast {
  def unapply(name: Name): Option[(String, String)] = name match {
    case SimpleName(first, last) => Some(first, last)
    case FullName(first, _, last) => Some(first, last)
    case _ => None
  }
}

val p: Person = ...
p match {
  case Person(FirstLast("Joe", last), age) => ...
}
In Decomat:
Copy code
object FirstLast {
  operator fun get(first: Pattern0<String>, last: Pattern0<String>) =
    customPattern2(first, last) { it: Name ->
      on(it).match(
        case(FullName[Is(), Is()])
          .then { first, last -> Components2(first, last) },
        case(SimpleName[Is(), Is()])
          .then { first, last -> Components2(first, last) }
      )
    }
}

// Then use the `FirstLast` custom pattern to match and extract data
val p: Person = ...
val out =
  on(p).match(
    case(Person[FirstLast[Is("Joe"), Is()], Is()]).then { (first, last), age -> ... }
  )
https://github.com/exoquery/decomat
K 4
🙌 2