1

I'm new in Kotlin I have a class Person with (name) and (age) property. How can I set the extension property for Person class like that

var Person.phone: Int
    get() = this.phone
    set(value) {this.phone = value}

How I can use setter in this case? Thank you.

FinalDest
  • 49
  • 2
  • 7
  • 1
    If I understand the question correctly, you want to have an extension property with a backing field. This is not possible, because extensions do not modify the classes. You can, however, try to emulate this behavior with a delegate, see [my answer to the question](https://stackoverflow.com/a/36511438/2196460) I linked as the duplicated. – hotkey Oct 17 '17 at 14:30
  • But how can I use the setter method? – FinalDest Oct 17 '17 at 14:36
  • Ah, just assign the value into the property: `person.phone = 12345` – hotkey Oct 17 '17 at 14:43
  • That's for Kotlin. And in Java, you need to call the static method on the class that corresponds to the file that declares the extension, e.g. `FilenameKt.setPhone(person, 12345);` – hotkey Oct 17 '17 at 14:45
  • 1
    I think it could be a recursive call? – FinalDest Oct 17 '17 at 14:45
  • Currently, it _is_. – Salem Oct 17 '17 at 14:46
  • In my opinion, the setter, in this case, is redundant of Kotlin, – FinalDest Oct 17 '17 at 14:47
  • Why? With a normal property you don't NEED to specify a setter. It's automatically implemented if it has a backing field. `val a = 3` is completely valid. – Salem Oct 17 '17 at 14:49
  • I mean when you extend a property (dont have backing field), you use the setter by assigning person.phone = 12345 but it's infinite recursive call. So, I think Kotlin should remove the setter in this case – FinalDest Oct 17 '17 at 14:53
  • That's not the point of an extension property. You are making the recursive call yourself, so _your_ code is causing infinite recursion. If you don't _want_ a setter, just use `val` instead of `var`. – Salem Oct 17 '17 at 15:31

1 Answers1

0

Not sure that Kotlin can accomplish what you want here.

From the docs:

Note that, since extensions do not actually insert members into classes, there's no efficient way for an extension property to have a backing field. This is why initializers are not allowed for extension properties. Their behavior can only be defined by explicitly providing getters/setters.

Since you can't add a backing field for your property, you can't really add that bit of stored data to the existing class this way.

You may instead have to extend Person to add more to it.

dillius
  • 506
  • 4
  • 12