Orest
Orest

Reputation: 6748

How to get name from Java enum in Kotlin

I have a project that is written with both Java and Kotlin languages and recently I faced next issue.

Let's say we have MyMonth enum:

public enum MyMonth {
    JAN("January"),
    FEB("February");

    private final String name;

    MyMonth(final String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
}

Then in Kotlin when we print the name of the month:

fun main() {
    val month = MyMonth.JAN
    println(month.name)
}

we get:

JAN

which is what is described in the documentation https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-enum/name.html, however actually the name should be January.

Is there a way to get a name in Kotlin that is specified in Java enum?

UPD: My Kotlin version is 1.3.30-release-170

UPD2: IDEA even shows me that name is coming from the getName() method defined in Java: enter image description here

UPD3: When we explicitly use .getName() it works, however it looks kind of weird

Upvotes: 3

Views: 9018

Answers (3)

Prabudda Fernando
Prabudda Fernando

Reputation: 509

enum is now low usage. You can use IntDef instead of enums.

@IntDef(MyMonth.JAN, MyMonth.FEB)
@Retention(AnnotationRetention.SOURCE)
annotation class MyMonth  {
    companion object {
        const val JAN = 0
        const val FEB = 1

        fun getDisplayString(toDoFilterTypes: Int): String {
            return when (toDoFilterTypes) {
                JAN -> "All"
                FEB -> "Job"
                else -> "N/A"
            }
        }
    }
}

Upvotes: 0

Minn
Minn

Reputation: 6124

You can call the getter directly instead of using the property syntax:

fun main() {
    val name = MyMonth.JAN.getName()
    println(name)
}

Upvotes: 5

Louis Wasserman
Louis Wasserman

Reputation: 198023

Your Java API has name as a private field. Nothing can access it, not in Java nor Kotlin.

If you want to access it, add e.g. the following to the Java API:

public String getMonthName() { return name; }

...and then access it from Kotlin as

val month = MyMonth.JAN.monthName

Upvotes: 3

Related Questions