Question

I'm new to Scala and right now I'm creating my first enumeration (with case classes to override toString).

package views.helper.button

abstract sealed class Size(identifier: Option[String])
{
    def this(identifier: String) = this( Some( identifier ) )

    override def toString: String = identifier match
    {
        case Some( identifier ) => "btn-" + identifier
        case _ => ""
    }

    case object Mini extends Size( "mini" )
    case object Small extends Size( "small" )
    case object Default extends Size( None )
    case object Large extends Size( "normal" )
}

Coming from a Java background this was my first attempt. Accessing the case objects like button.Size.Mini seems very natural to me. But it looks like I'm unable to access the class' inner case objects. Placing them below the Size class works fine but results in a confusing namespace.

Why is that? How would you model this behavior? Can this be done more elegant by an object extending Enumeration (I figured toString would become an issue..)?

Was it helpful?

Solution

If you want to use case class, you need to put the case object in the companion object of Size (equivalent to static visibility)

package views.helper.button

abstract sealed class Size(identifier: Option[String])
{
    def this(identifier: String) = this( Some( identifier ) )

    override def toString: String = identifier match
    {
        case Some( identifier ) => "btn-" + identifier
        case _ => ""
    }
}

object Size {
    case object Mini extends Size( "mini" )
    case object Small extends Size( "small" )
    case object Default extends Size( None )
    case object Large extends Size( "normal" )
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top