Skip to content
TheChatArchiveThe Chat Archive
Geminigemini-2.5-pro-preview-05-06· GoogleHugging Face LMArena Human Preference 140K

Please explain type level programming in Scala 3, and provide a real world example for a…

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Claudeclaude-sonnet-4-20250514’s answer.
  1. User

    Please explain type level programming in Scala 3, and provide a real world example for a use case.

  2. Gemini Assistant

    Okay, let's dive into Type-Level Programming (TLP) in Scala 3.

    What is Type-Level Programming?

    At its core, type-level programming means performing computations at compile time using the type system itself. Instead of manipulating values (like integers or strings) at runtime, you manipulate types.

    • "Values" are Types: Literal types (1, "hello", true), custom types (User, Order), or type parameters (A, B).
    • "Functions" are Type Constructors/Aliases: These take types as input and produce new types as output. Scala 3's match type is a powerful way to define these "type-level functions."
    • "Output" is a Type or a Compile-Time Error: The result of a type-level computation is a new, refined type, or the compiler stops with an error if certain constraints (encoded in types) are not met.

    The primary goal is to move more checks and logic from runtime to compile time, leading to:

    1. Increased Safety: Catching errors earlier in the development cycle.
    2. Enhanced Performance: Computations done at compile time don't need to be re-done at runtime.
    3. More Expressive APIs: Types can guide users towards correct API usage and prevent invalid states or operations.

    Key Scala 3 Features for Type-Level Programming:

    Scala has always had some TLP capabilities (e.g., implicit resolution for type classes), but Scala 3 significantly enhances them:

    1. Match Types:

      • The star of the show for TLP in Scala 3. They allow defining functions that operate on types using pattern matching.
      • Syntax: type Result[X] = X match { case A => B; case C => D }
    2. Literal Types (Singleton Types):

      • Types that represent a single specific value, e.g., 1, "foo", true.
      • Crucial for representing specific constants at the type level (like the size of an array or a specific configuration key).
    3. inline and the scala.compiletime package:

      • inline: A modifier that ensures a method or value is evaluated at compile time (if possible) and its code is inlined.
      • compiletime.ops.int.*, compiletime.ops.string.*, etc.: Provide type-level operations on literal types (e.g., ops.int.+ for adding two literal integer types).
      • compiletime.constValue[T]: If T is a literal type, this extracts its corresponding runtime value at compile time.
      • compiletime.error("message"): Allows you to explicitly generate a compile-time error.
      • compiletime.S[N]: Helper to get N-1 for a positive literal integer type N.
    4. Type Lambdas:

      • Anonymous functions for types: [X] =>> F[X]. Useful for abstracting over type constructors.
    5. Implicit Resolution (Givens/Using):

      • Still fundamental for "proving" properties about types at compile time (e.g., "type T has an instance of type class Encoder).

    A Simple Illustrative Example (Type-Level Adder):

    Before a real-world example, let's see a very basic TLP function:

    import scala.compiletime.ops.int.+
    
    // A type-level function that adds two literal Int types
    type Add[A <: Int, B <: Int] = A + B
    
    // Usage:
    val sumType: Add[2, 3] = 5 // sumType is an alias for the literal type 5
    val sumValue: 5 = sumType  // Can assign 5 to it
    
    // Proof:
    val result: Int = scala.compiletime.constValue[Add[10, 20]] // result = 30 at runtime
    println(s"10 + 20 (type-level) = $result")
    
    // You can use this in type signatures:
    def takesSpecificSum(x: Add[7, 8]): Unit = println(s"Got: $x") // x must be 15
    takesSpecificSum(15)
    // takesSpecificSum(16) // Compile-time error!
    

    Real-World Example: Fixed-Size Vectors (SizedList)

    Let's create a SizedList where the size is part of its type. This allows us to prevent IndexOutOfBoundsException at compile time for operations like get.

    Goal:

    • A list type SizedList[A, N] where A is the element type and N is the compile-time known size (a literal Int).
    • A get(index) method that only compiles if index is a literal Int and 0 <= index < N.
    • An append method that correctly computes the new size at the type level.
    import scala.compiletime.{constValue, error, S} // S is for successor, e.g., S[N] is N-1 if N > 0
    import scala.compiletime.ops.int.{+, <, >=, ToString} // Type-level integer operations
    
    // Our SizedList class
    class SizedList[+A, N <: Int] private (private val elements: List[A]) {
      // Runtime check for constructor integrity (good practice, though not TLP itself)
      // This ensures that the runtime list actually matches the type-level size.
      // ValueOf[N] is needed to get the runtime value of the type N.
      locally {
        val expectedSize = constValue[N]
        require(elements.length == expectedSize,
          s"Internal error: List length ${elements.length} does not match type-level size $expectedSize")
      }
    
      // Type-level size accessor (returns the literal type N)
      def size: N = constValue[N] // constValue can turn a literal type into its runtime value
    
      // Safe get method
      // `transparent inline` allows the compiler to "see through" this method at compile-time.
      transparent inline def get[Idx <: Int](inline index: Idx): A = {
        // `constexpr` is a helper to evaluate a type-level boolean at compile-time
        inline if constexpr[Idx >= 0 && Idx < N] then
          elements(index) // Safe: index is known to be in bounds
        else
          // `compiletime.error` generates a custom compile-time error message.
          // `ToString` converts a type-level Int to a type-level String for the error message.
          error("Index " + constValue[ToString[Idx]] + " is out of bounds for SizedList of size " + constValue[ToString[N]])
      }
    
      // Append another SizedList
      // The result type will have a size that is the sum of the two list sizes.
      def append[B >: A, M <: Int](other: SizedList[B, M]): SizedList[B, N + M] =
        new SizedList[B, N + M](this.elements ++ other.elements)
    
      // A way to convert to a regular List
      def toList: List[A] = elements
    
      override def toString: String = s"SizedList(${elements.mkString(", ")}) (type-level size: ${constValue[N]})"
    
      // Helper to evaluate a Boolean type at compile-time
      private transparent inline def constexpr[B <: Boolean]: Boolean =
        constValue[B]
    }
    
    // Companion object with factory methods
    object SizedList {
      def empty[A]: SizedList[A, 0] = new SizedList[A, 0](Nil)
    
      // A factory method. In a real library, you might use macros to infer N from varargs.
      // For simplicity, we require the user to provide elements and assert the type N.
      // The constructor's `require` will do a runtime check.
      def of[N <: Int]: SizedListBuilder[N] = new SizedListBuilder[N]
    
      // Helper class for curried type application to make `of[3]("a", "b", "c")` syntax work
      class SizedListBuilder[N <: Int] {
        def apply[A](elements: A*)(using ValueOf[N]): SizedList[A, N] = {
          if (elements.length != constValue[N]) {
            throw new IllegalArgumentException(s"Expected ${constValue[N]} elements for SizedList of type size N, but got ${elements.length}")
          }
          new SizedList[A, N](elements.toList)
        }
      }
    }
    
    // --- Let's use it! ---
    object SizedListDemo {
      def main(args: Array[String]): Unit = {
        // Creating SizedLists
        val l0 = SizedList.empty[Int]
        println(l0) // SizedList() (type-level size: 0)
    
        val l3: SizedList[String, 3] = SizedList.of[3]("alpha", "beta", "gamma")
        println(l3) // SizedList(alpha, beta, gamma) (type-level size: 3)
    
        // --- Compile-time safe `get` ---
        val firstElement: String = l3.get(0) // Compiles, firstElement = "alpha"
        println(s"First element: $firstElement")
    
        val secondElement: String = l3.get(1) // Compiles, secondElement = "beta"
        println(s"Second element: $secondElement")
    
        // val invalidAccess1 = l3.get(3)
        // ^^^ COMPILE ERROR: Index 3 is out of bounds for SizedList of size 3
    
        // val invalidAccess2 = l3.get(-1)
        // ^^^ COMPILE ERROR: Index -1 is out of bounds for SizedList of size 3
    
        val anIndex = 2 // This is a runtime Int, not a literal type
        // val runtimeIndexAccess = l3.get(anIndex)
        // ^^^ COMPILE ERROR: (usually something about `anIndex` not being a constant type or `Idx` not being a subtype of `Int & Singleton`)
        // The `get` method expects a compile-time constant literal for the index.
    
        // --- Type-safe `append` ---
        val l2: SizedList[String, 2] = SizedList.of[2]("delta", "epsilon")
        val l5: SizedList[String, 5] = l3.append(l2) // l5 has type SizedList[String, 3 + 2], which is SizedList[String, 5]
        println(l5) // SizedList(alpha, beta, gamma, delta, epsilon) (type-level size: 5)
        println(s"Element at index 4 of l5: ${l5.get(4)}") // Compiles
    
        //val l5Oops: SizedList[String, 6] = l3.append(l2) // Type mismatch! Expected SizedList[String, 6], found SizedList[String, 5]
        // ^^^ COMPILE ERROR!
    
        // Example of using constValue to get the size at runtime
        val sizeOfL5: Int = constValue[l5.size.type] // l5.size has type 5 (literal type), so constValue[5] is 5
        println(s"Runtime size of l5: $sizeOfL5") // Prints 5
      }
    }
    

    Explanation of the SizedList Example:

    1. SizedList[+A, N <: Int]: N is a subtype of Int, constrained to be a literal integer type (e.g., 0, 1, 3).
    2. transparent inline def get[Idx <: Int](inline index: Idx):
      • transparent inline: Crucial. It tells the compiler to evaluate this method at compile time if possible and "see through" its implementation.
      • Idx <: Int: The index type. For compile-time checking, index must be a literal passed directly (e.g., l3.get(0)).
      • inline index: Ensures index is a compile-time constant.
    3. inline if constexpr[Idx >= 0 && Idx < N]:
      • Idx >= 0 and Idx < N are type-level boolean expressions using compiletime.ops.int.>= and compiletime.ops.int.<. The result is a literal boolean type (true.type or false.type).
      • constexpr[BooleanType] (our helper) uses compiletime.constValue to convert this boolean type into a runtime boolean value that the inline if can use for its compile-time branching.
    4. compiletime.error(...): If the inline if condition is false at compile time, this branch is taken, and a compile-time error is emitted.
    5. append[...](...): SizedList[B, N + M]:
      • N + M uses compiletime.ops.int.+ to compute the new size type by adding the two literal integer types N and M. The result is a new literal integer type.
    6. SizedList.of[N] factory:
      • The SizedListBuilder with its apply method is a common pattern to allow specifying the type parameter N first (e.g., SizedList.of[3]) and then the elements. The using ValueOf[N] allows the apply method to get the runtime value of N for the require check, ensuring that the number of elements provided matches the declared type-level size N.

    Benefits Demonstrated by SizedList:

    • Safety: IndexOutOfBoundsException for get is caught at compile time.
    • Correctness: The append operation correctly computes and reflects the new size in its return type.
    • Expressiveness: The size of the list is now part of its static type, conveying more information to the programmer and compiler.

    Drawbacks and Considerations:

    • Complexity: Type-level code can be harder to write, read, and debug than runtime code. Error messages from the compiler, while improving, can sometimes be cryptic.
    • Compilation Time: Heavy use of TLP can increase compilation times.
    • Limitations: Not all computations are feasible or practical at the type level. The system for literal type operations is powerful but not as fully fledged as runtime computations.
    • Ergonomics: Creating instances (like SizedList) often requires careful factory design or macros to infer type-level information (like size from varargs) smoothly.

    In summary, type-level programming in Scala 3, especially with match types and the compiletime facilities, offers a powerful way to build more robust and performant libraries and applications by leveraging the compiler to enforce complex invariants and perform computations before runtime. The SizedList example showcases how these features can be used to add significant safety to common operations.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.