99 Problems in Scala

Just another WordPress.com weblog

Enums in Scala

Posted by rbpasker on April 25, 2009

Amazingly enough, no example of how to do this is in either Programming in Scala or on the Scala-lang.org website.

there are a few Scala-isms here.

First, since there’s no member variables in State, a trait is more appropriate than a class.

Second, by using the keyword “sealed,” you specify that no other instances of this trait will be found in any other source file. That means that the code generated for the match expression doesn’t need an “default”, and you are guaranteed that the match will always have a case to choose from.

Lastly, by specifying the case classes as “object” you get a singleton subclass for each discrete state.

sealed trait State
case object Closed extends State
case object Open extends State
case object Interrupted extends State



scala> val theState:State=Open
theState: State = Open

scala> theState match
{
case Open => println("o")
case Closed => println("c")
case Interrupted => println("i")
}
o

One Response to “Enums in Scala”

  1. Bob said

    Your isPalindrome fails on List(1,2,3,1) because you are only checking if the head == tail and your test cases aren’t very complete. Try this one:

    def isPalindrome[T](l: List[T]) : Boolean = l match {
    case Nil => true
    case _::Nil => true
    case h::t => (h == t.reverse.head) && isPalindrome(t.reverse.tail)
    }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

 
Follow

Get every new post delivered to your Inbox.