Skip to content

Instantly share code, notes, and snippets.

@chuwy
Created April 1, 2024 06:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chuwy/1f2cf3c4f3d9d1ab07fe480744d1ae22 to your computer and use it in GitHub Desktop.
Save chuwy/1f2cf3c4f3d9d1ab07fe480744d1ae22 to your computer and use it in GitHub Desktop.
A Scala 3 match type that checks that all elements of a tuple match a certain (sub)type
import scala.compiletime.ops.boolean.&&
type AllSubtypesOfMatch[T <: Tuple, Super] <: Boolean = T match
case EmptyTuple =>
true
case h *: t =>
h match
case Super => AllSubtypesOfMatch[t, Super]
type AllSubtypesOf[T <: Tuple, Super] = AllSubtypesOfMatch[T, Super] =:= true
def processErrors[T <: Tuple](errors: T)(using AllSubtypesOf[T, Throwable]) = ()
processErrors((new RuntimeException("foo"), new IllegalAccessError("boom"))) // ok
// processErrors((new RuntimeException("foo"), new IllegalAccessError("boom"), "foo")) // not ok
@chuwy
Copy link
Author

chuwy commented Apr 1, 2024

Another way to ensure consistency of the tuple elements:

  1. Introduce generic type Foo[_]
  2. Have a signature of def ofTuple[T <: Tuple: Tuple.IsMappedBy[Foo]](tup: T)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment