how can I declare a sealed case class in Scala ?
- User
how can I declare a sealed case class in Scala ?
- Assistant
In Scala, you can declare a sealed case class by using the
sealedkeyword before thecase classkeyword. Here's an example:sealed case class Animal(name: String) case class Dog(name: String, breed: String) extends Animal(name) case class Cat(name: String, color: String) extends Animal(name)In this example,
Animalis a sealed trait that represents the base type for all animals.DogandCatare case classes that extendAnimaland add additional fields. BecauseAnimalis sealed, all its subclasses must be defined in the same file. This allows the Scala compiler to exhaustively pattern match on the subclasses.You can also define a sealed case class without any fields, for example:
sealed case class Message(content: String) case object Info extends Message("This is an info message") case object Warning extends Message("This is a warning message") case object Error extends Message("This is an error message")In this example,
Messageis a sealed case class that represents different types of messages.Info,Warning, andErrorare case objects that extendMessageand represent specific message types.You can then use pattern matching to handle different message types:
val message = Info message match { case Info => println("This is an info message") case Warning => println("This is a warning message") case Error => println("This is an error message") }In this example, the pattern matching expression will match the
Infocase and print "This is an info message".I hope this helps! Let me know if you have any questions.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.