10

Is there a way to rename the default getters and setters in Kotlin? I have a property named in snake_case, but I still want the getters and setters to be named in camelCase.

The closest I've gotten is something like

private var property_name = Color.BLACK
private set
fun setPropertyName(c: Color) { property_name = c }
fun getPropertyName() = property_name

Is there a way to do this without hiding the getters and setters and defining new methods?

Jeffmagma
  • 452
  • 2
  • 8
  • 20
  • Are you trying to name these using snake case for the benefit of some other system (i.e. JSON serdes?). Why use the non standard naming for properties? That context might lead to completely different answers to help you accomplish what you are trying. (in other words, is this an XY problem http://xyproblem.info/) – Jayson Minard Jun 08 '17 at 12:10
  • @JaysonMinard I just like the snake case style when naming my variables, but the project requirements need camel case getters and setters – Jeffmagma Jun 08 '17 at 21:26

2 Answers2

26

If you just want to change the name and not the functionality, you can also scope the annotation like so:

@get:JvmName("getPropertyName")
@set:JvmName("setPropertyName")
var property_name = Color.BLACK
Ruckus T-Boom
  • 4,566
  • 1
  • 28
  • 42
14

It is described in the section on handling signature clashes: https://kotlinlang.org/docs/reference/java-to-kotlin-interop.html#handling-signature-clashes-with-jvmname

val x: Int
    @JvmName("getX_prop")
    get() = 15

So @JvmName("getPropertyName") get should work.

Kiskae
  • 24,655
  • 2
  • 77
  • 74