Back to Scala3

E182: Not Constant

docs/_docs/reference/error-codes/E182.md

3.8.41.4 KB
Original Source

E182: Not Constant

This error occurs when attempting to use constValue (or similar compile-time operations) on a type that is not a constant type.

A constant type in Scala 3 is a type that represents a single, literal value known at compile time, such as 1, "hello", or true. Types like Int, String, or opaque types that cannot be resolved to a single constant value cannot be used where a constant type is required.


Example

scala
import scala.compiletime.constValue

def example(): Int = constValue[Int]

Error

scala
-- [E182] Type Error: example.scala:3:32 ---------------------------------------
3 |def example(): Int = constValue[Int]
  |                                ^^^
  |                        Int is not a constant type; cannot take constValue

Solution

Use a literal singleton type instead:

scala
import scala.compiletime.constValue

def example(): Int = constValue[42]

Or use a type alias that resolves to a constant type:

scala
import scala.compiletime.constValue

type MyConstant = 100
def example(): Int = constValue[MyConstant]
<!-- SOURCE-ONLY: Remove the notice below once this page has been manually updated. --> <aside class="warning"> This reference page was created with LLM assistance - the description of the error code may not be accurate or cover all possible scenarios. </aside>