Back to Scala3

E140: Illegal Cyclic Type Reference

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

3.8.41.6 KB
Original Source

E140: Illegal Cyclic Type Reference

This error occurs when a type alias or type definition references itself, either directly or through a chain of other type aliases, creating a cycle.

Type aliases must eventually resolve to a concrete type. When a type refers back to itself without eventually resolving to a non-circular definition, the compiler cannot determine what the type actually represents.

Use the -explain-cyclic flag to get a detailed trace of how the cyclic reference was discovered.


Example

scala
type A = B
type B = A

Error

scala
-- [E140] Cyclic Error: example.scala:1:5 --------------------------------------
1 |type A = B
  |     ^
  |illegal cyclic type reference: alias B of type A refers back to the type itself
  |
  |The error occurred while trying to compute the signature of type A
  |  which required to explore type B for cyclic references
  |  which required to explore type A for cyclic references
  |
  | Run with both -explain-cyclic and -Ydebug-cyclic to see full stack trace.

Solution

scala
// Break the cycle by using a concrete type
type A = Int
type B = A
scala
// Alternative: If recursion is needed, use a class or trait
trait A:
  def next: A
<!-- 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>