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

type A = B
type B = A

Error

-- [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

// Break the cycle by using a concrete type
type A = Int
type B = A
// Alternative: If recursion is needed, use a class or trait
trait A:
  def next: A