Skip to content
The Chat Archive
mistral-medium· Mistral AI Arena Human Preference 55K

how can I declare a sealed case class in Scala ?

  1. User

    how can I declare a sealed case class in Scala ?

  2. Assistant

    In Scala, you can declare a sealed case class by using the sealed keyword before the case class keyword. 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, Animal is a sealed trait that represents the base type for all animals. Dog and Cat are case classes that extend Animal and add additional fields. Because Animal is 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, Message is a sealed case class that represents different types of messages. Info, Warning, and Error are case objects that extend Message and 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 Info case and print "This is an info message".

    I hope this helps! Let me know if you have any questions.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.