Override enum toString() in Kotlin?

In primary constructors, you need to use var or val if you want it to be globally visible (which includes locally in class/enum methods). Otherwise it's just locally in the initialization. Consider this:

public GuideType (String type) {}

Compared to this:

private String type;
public GuideType (String type) { this.type = type; }
// Getters and setters

Without var or val, it'll produce something roughly equivalent to the first one1. You can also access it in the init block, and in class-level variable initialization. So, in order to use it in a method, prepend val:

enum class GuideType(val type: String) { ... }

Since the variable (probably) won't be changed, it should be a val. You can, of course, use var too.


Note that this applies to primary constructors. Secondary constructors work differently.


1: Kotlin will also produce a bunch of null-safety stuff including @NotNull and null checks, but the code is still the rough equivalent


Default constructor params need to be either var or val to be accessible outside the init block. Also you need to add semicolor after last enum item to add any new functions or overrides.

enum class GuideType(var type: String) {
    DEF_TYPE("default");

    override fun toString(): String {
        return type // working!
    }
}

Tags:

Android

Kotlin