Scala3 enum of enum

How can I represent ASTs using enum like

enum AST:
    enum Statement:
        case Block, If, While, For
    enum Expression:
        case Constant:
            case Number, String
        case BinaryExpr

My current solution is


trait AST

enum Statement extends AST:
  case BlockStmt(asts: List[AST])
  case IfStmt(condition: AST, `then`: BlockStmt, `else`: Some[BlockStmt])
  case WhileStmt(condition: AST, body: BlockStmt)

enum Expression extends AST:
  case Identifier(name: String)
  case StringLit(str: String)

By doing this, I am not able to represent Number and String <: Constant

Enums are syntactic sugar for the “sealed trait / case classes” pattern, so you can convert it to a sealed trait:

sealed trait Expression extends AST
enum Constant extends Expression:
  case Number, String
case class BinaryExpr(e1: Expr, e2: Expr) extends Expression
2 Likes