Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save deanwampler/a98176efc5eb200c838cb8ac4a1c1bbd to your computer and use it in GitHub Desktop.
Save deanwampler/a98176efc5eb200c838cb8ac4a1c1bbd to your computer and use it in GitHub Desktop.
// Adapted from Programming Scala, Third Edition code examples.
// https://github.com/deanwampler/programming-scala-book-code-examples
// src/script/scala/progscala3/typesystem/matchtypes/DepTypedMethods.scala
type ElemR[X] = X match // "R" for "recursive"
case String => Char
case Array[t] => ElemR[t]
case Iterable[t] => ElemR[t]
case Option[t] => ElemR[t]
case AnyVal => X
import compiletime.asMatchable
def first[X](x: X): ElemR[X] = x.asMatchable match
case s: String => s.charAt(0)
case a: Array[t] => first(a(0))
case i: Iterable[t] => first(i.head)
case o: Option[t] => first(o.get)
case x: AnyVal => x
// Define some types
case class C(name: String)
object O
first("one") // val res0: Char = o
first(Array(2.2, 3.3)) // val res1: Double = 2.2
first(Seq("4", "five")) // val res2: Char = 4
first(6) // val res3: Int = 6
first(true) // val res4: Boolean = true
first(O) // val res5: ElemR[O.type] = O$@4853f592
first(C("Dean")) // val res6: ElemR[C] = C(Dean)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment