Take for example the Regions
enum from AWS 1.11 java sdk. This class contains a String getName()
method. When developing with the AWS SDK in Kotlin, this method is provided as
Regions.EU_CENTRAL_1.name
The IntelliJ auto completion popup even says (from getName()) to let you know that the compiler treats the getter like a property.
The problem becomes apparent when you notice that
new AmazonS3ClientBuilder
.standard()
.withRegion(Regions.EU_CENTRAL_1.getName())
.build()
works in Java, while the equivalent
AmazonS3ClientBuilder
.standard()
.withRegion(Regions.EU_CENTRAL_1.name)
.build()
does not work in Kotlin. Printing the following with Java shows why this is the case:
System.out.println(Regions.EU_CENTRAL_1.getName()); // prints "eu-central-1"
System.out.println(Regions.EU_CENTRAL_1.name()); // prints "EU_CENTRAL_1"
How do I access a .getName()
method on a Java enum from Kotlin, as Kotlin prefers the .name()
method instead?
As suggested from the comments:
// Kotlin
Regions.EU_CENTRAL_1.name
in Kotlin resolves to
// Java
Regions.EU_CENTRAL_1.name()
in Java, while
// Kotlin
Regions.EU_CENTRAL_1.getName()
can be used to access the function getName()
of the Regions
enumeration.
This in turn leads to the question: What are the specific kotlin compiler java method name to property resolution rules?