2

In a Java Enum it is possible to add a non static method that works based on that enums instance.

So given the following enum this code TestEnum.FOO.getName(); would print "foo"

public static enum TestEnum {
    FOO("foo"),
    BAR("bar");
    private final String name;

    private TestEnum(String name) {
        this.name = name;
    }

    public String getName() {
        return this.name;
    }
}

What is the simplest way to do this in scala?

Busti
  • 5,492
  • 2
  • 21
  • 34
  • In your comment to Markus answer you mention a *Library* which expects an *enum*. Do you mean like ` & SomeInterface>`? Then I think, you cannot create anything in scala that will fit in there. – Sascha Kolberg Aug 21 '15 at 18:36
  • I don't think so. I've tried many different approaches now. I now made a more general Java enum. I was just hoping to find a solution here. – Busti Aug 21 '15 at 19:03

1 Answers1

2

You can define abstract members inside the trait and then implement them in the concrete cases:

sealed trait TestEnum { val name: String }
case object Foo extends TestEnum { val name = "foo" }
case object Bar extends TestEnum { val name = "foo" }

demonstration in REPL:

scala> val (foo,bar): (TestEnum,TestEnum) = (Foo,Bar)
foo: TestEnum = Foo
bar: TestEnum = Bar
scala> foo.name
res1: String = "foo"
scala> bar.name
res2: String = "bar"

Edit: You can define getName in the TestEnum accessing the name like this:

sealed trait TestEnum { val name: String; def getName = name }
case object Foo extends TestEnum { val name = "foo" }
case object Bar extends TestEnum { val name = "bar" }

Or you can also just forget about the val and use:

sealed trait TestEnum { def getName }
case object Foo extends TestEnum { def getName = "foo" }
case object Bar extends TestEnum { def getName = "bar" }
Markus1189
  • 2,829
  • 1
  • 23
  • 32
  • That is great but the Library I'm using expects me to use an enum that implements an Interface containing the `getName()` method. – Busti Aug 21 '15 at 17:57
  • well you can name the `val` `getName` or define `getName` in the trait as well – Markus1189 Aug 21 '15 at 18:06
  • Better, make your sealed trait extend this interface your library expects. – Asa Aug 21 '15 at 19:27