-1

Disclaimer: I'm new to Java and Kotlin enums.

In Java 9+, if I do this:

enum Animal {
    DOG("woof"), CAT("meow");
    public String sound;

    Animal(String sound) {
      this.sound = sound;
    }
}

class Foo {
    public static void main(String[] args) {
        List<Animal> foo = List.of(Animal.DOG, Animal.CAT);
        System.out.println(Animal.values());
}

...and then set a breakpoint on the println(), my IntelliJ IDEA debugger shows that each enum element calls itself (e.g., {Animal@448}) by its "name" not its "value" (sound).

foo = {ImmutableCollections$List12@444} size =2
  0 = {Animal@448} "DOG"
     sound = "woof"
     name = "DOG"
     ordinal = 0
  1 = {Animal@449} "CAT"
     sound = "meow"
     name = "CAT"
     ordinal = 1

But when I try similar code using okhttp.Protocol (an enum written in Kotlin), I see the opposite happen: each element refers to itself (e.g., Protocol@566) using the "value" (protocol) instead of the "name":

import okhttp3.Protocol;

class Foo {
    public static void main(String[] args) {
        List<Protocol> foo = List.of(Protocol.HTTP_1_0, Protocol.HTTP_1_1);
        System.out.println(Animal.values());
}

...which you can see as follows:

foo = {ImmutableCollections$List12@562} size =2
  0 = {Protocol@566} http/1.0
    protocol = "http/1.0"
    name = "HTTP_1_0"
    ordinal = 0
  1 = {Protocol@567} http/1.1
    protocol = "http/1.1"
    name = "HTTP_1_1"
    ordinal = 1
}

How can I make Java use the "value" like in Kotlin? For reference, here's the relevant Kotlin "primary constructor":

enum class Protocol(private val protocol: String) {
  /**
   * An obsolete plaintext framing that does not use persistent sockets by default.
   */
  HTTP_1_0("http/1.0"),
mellow-yellow
  • 1,670
  • 1
  • 18
  • 38

1 Answers1

2

In the source code of Protocol, you can see that they overrode toString():

override fun toString(): String = protocol

You can do this in Java enums as well:

enum Animal {
    DOG("woof"), CAT("meow");
    public String sound;

    Animal(String sound) {
      this.sound = sound;
    }

    @Override
    public String toString() {
        return sound;
    }
}
Tenfour04
  • 83,111
  • 11
  • 94
  • 154