enum

Benefits of sealed traits in Scala (like enum in Java) alvin December 27, 2016 - 3:10pm

As a quick note about traits in Scala, this StackOverflow page makes a few good points about sealed traits:

How to create and use Scala enumerations

This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 10.26, “How to Create and Use Scala Enumerations”

Problem

You want to use an enumeration (a set of named values that act as constants) in your application.

Solution

Extend the scala.Enumeration class to create your enumeration:

How to use Scala enums (Enumeration)

Problem: You want to use an enumeration (a set of named values that act as constants) in your Scala application.

Solution

Extend the scala.Enumeration class to create your enumeration:

package com.acme.app {

    object Margin extends Enumeration {
        type Margin = Value
        val TOP, BOTTOM, LEFT, RIGHT = Value
    }

}

Then import the enumeration to use it in your application:

Java enum examples/tutorial

Java enum FAQ: Can you share some Java enum examples, such as how to declare a Java enum, and how to use a Java enum in a for loop, if then statement, and Java switch statement?

As described in Sun's Java documentation, a Java enum "is a type whose fields consist of a fixed set of constants ... you should use enum types any time you need to represent a fixed set of constants." Let's take a look at some Java enum examples to see how this works.

Java enum ‘for’ loop examples alvin September 18, 2009 - 7:31pm

Java enum FAQ: Can you share some Java enum for loop examples?

I’ve written several Java enum tutorials recently, (Java enum examples tutorial, Java enum switch example, and Java enum toString tutorial), and before leaving the “Java enum” topic, I thought it would be good to show one example that just focuses on the Java enum for loop syntax.

A Java enum toString example

Java enum FAQ: Can you share a Java enum toString example?

I haven’t tried this before, but I was just working on several Java enum examples (Java enum examples tutorial, Java enum switch example), and I thought I’d take a look at the Java enum toString behavior.

To that end I wrote the following Java enum “toString” example class:

A Java enum switch/case statement example

Java enum FAQ: Can you share a Java enum switch example, i.e., how to use an enum with a Java switch statement?

In my earlier Java enum examples tutorial, I demonstrated how to declare a simple Java enum, and then how to use a Java enum with a variety of Java constructs, including a Java switch statement, a for loop, and an if/then statement.