Search code examples
scalasealedcompanion-object

Scala - Create a List of case objects that extend an sealed abstract class


I'm trying to create a List of case objects in a companion object. The objects all inherit from a sealed abstract class. But the compiler is saying "not found: value CompositeSpectrum" and so on for each item in the List. The sealed class and case objects all compile fine, it's just when I try to make the List in the companion object that I get errors.

sealed abstract class Peculiarity(val abbreviation: String, val description: String) {
    case object CompositeSpectrum extends Peculiarity("comp", "composite spectrum")
    case object NebularFeaturesPresent extends Peculiarity("neb", "nebular features present")
    case object ShellStar extends Peculiarity("sh", "shell star")
    case object Uncertainty extends Peculiarity(":", "uncertainty")
    case object VariableSpectralFeatures extends Peculiarity("var", "variable spectral features")
    case object WeakFeatures extends Peculiarity("wl", "weak features")
    case object VeryBroadAbsorptionFeatures extends Peculiarity("nn", "very broad absorption features")
    case object BroadAbsorptionFeatures extends Peculiarity("n", "broad absorption features")
    case object EmissionLinesPresent extends Peculiarity("e", "emission lines present")
    case object NIIIandHEIIEmission extends Peculiarity("f", "NIII and HeII emission (O stars)")
    case object EnhancedMetalFeatures extends Peculiarity("m", "enhanced metal features")
    case object OtherPeculiarity extends Peculiarity("p", "other peculiarity")
    case object VeryNarrowAbsorptionLines extends Peculiarity("s", "very narrow absorption lines")
}

object Peculiarity {
    val peculiarities = List[Peculiarity](
        CompositeSpectrum,
        NebularFeaturesPresent,
        ShellStar,
        Uncertainty,
        VariableSpectralFeatures,
        WeakFeatures,
        VeryBroadAbsorptionFeatures,
        BroadAbsorptionFeatures,
        EmissionLinesPresent,
        NIIIandHEIIEmission,
        EnhancedMetalFeatures,
        OtherPeculiarity,
        VeryNarrowAbsorptionLines)
}

Solution

  • Because those objects don't exist unless they are referenced from an instance of the type of Peculiarity because they are declared as internal objects to Peculiarity.

    val pec = new Peculiarity("","") {}
    val peculiarities = List[Peculiarity](
      pec.CompositeSpectrum,
      pec.NebularFeaturesPresent,
      ...
    

    But I doubt that what you after, you can just move the declaration to outside the abstract class

      sealed abstract class Peculiarity(val abbreviation: String, val description: String)
      case object CompositeSpectrum extends Peculiarity("comp", "composite spectrum")
      case object NebularFeaturesPresent extends Peculiarity("neb", "nebular features present")
      ...
    

    And then your declaration would work just fine.