Skip to content

Instantly share code, notes, and snippets.

@bishabosha
Created January 28, 2022 09:51
Show Gist options
  • Save bishabosha/90f9f6dc76fe69fa949904b722e018a7 to your computer and use it in GitHub Desktop.
Save bishabosha/90f9f6dc76fe69fa949904b722e018a7 to your computer and use it in GitHub Desktop.
Statically get the ordinal of any child of a sum-type in Scala
import scala.compiletime.ops.int.S
import scala.compiletime.constValue
import scala.deriving.Mirror
object Tuples {
type IndexOf[Q, T <: Tuple, I <: Int] <: Int = T match {
case EmptyTuple => -1
case Q *: ts => I
case _ *: ts => IndexOf[Q, ts, S[I]]
}
}
object Sums {
inline def ordinalOf[C <: S, S](using m: Mirror.SumOf[S]): Int = {
type Index = Tuples.IndexOf[C, m.MirroredElemTypes, 0]
constValue[Index]
}
}
enum Foo {
case A
case B
case C
}
@main def Test =
inline def fooOrd[T <: Foo] = Sums.ordinalOf[T, Foo]
assert(fooOrd[Foo.A.type] == 0)
assert(fooOrd[Foo.B.type] == 1)
assert(fooOrd[Foo.C.type] == 2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment