Home > Software engineering >  Is it possible to get a reference to a variable in Kotlin?
Is it possible to get a reference to a variable in Kotlin?

Time:03-25

Is it possible to get a reference to a variable in Kotlin?

Example:

var vIndex = 0

::vIndex

Not supported [Variable references are not yet supported]

Can this be bypassed somehow?

CodePudding user response:

Rather than writing:

var vIndex = 0
val propertyReference = ::vIndex // error

You can put the local property into an anonymous object:

val foo = object {
    var vIndex = 0
    // you can also put other local properties that you want to reference here
    // in the same object, provided that they are in the same scope
}
val propertyReference = foo::vIndex

propertyReference here will be of type KMutableProperty0<Int>, just as you would expect. You can access/mutate foo.vIndex the same way you can the local property vIndex.

Of course, this has the additional overhead of creating an additional class file for the anonymous object, but alas, a workaround is a workaround.

CodePudding user response:

As stated in your question, (local) variable references are not yet supported. But you can have a reference to a property, i.e. you can write:

class VariableReferences {

    var vIndex = 0

    var ref = ::vIndex
}
  • Related