Question

I am trying to model a DSL in Scala. (I am very new to Scala so I might be missing something trivial, in which case apologies). The DSL supports a very simple type system, where entities called 'Terms' can have a type, which either extends Object by default, or can extend other types, which in their own right eventually extend another type or Object.

I am trying to model this type hierarchy in Scala using a case class:

case class TermType(name: String, superType: TermType)

However, I want to be able to support a 'default' case (the one where the type just extends 'Object'), without having to specify the super type, so something of the sort:

//the following does not work, just illustrating what I want to achieve
case class TermType(name: String, superType: TermType = new TermType("Object", ???))

Not sure if it is the right approach. I wish to avoid putting nulls or stuff like that. I don't know if going the Option way is in some way better (if it works at all).

How is it best to go about it?

Was it helpful?

Solution

for example:

sealed abstract class TermType
case class TermTypeSimple(name: String) extends TermType
case class TermTypeWithParen(name: String, parent: TermType) extends TermType

Other way:

case class TermType(name: String, superType: Option[TermType] = None)

With usages:

TermType("Hi")
TermType("Buy", Some(TermType("Beer"))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top