"Convert property getter to initializer" - but they aren't the same thing, are they?

Viewed 120

I'm using IntelliJ with a mixed Java/Kotlin project. In one of my Kotlin files, I have this property:

override val value: String
    get() {
        return webElement.getAttribute("value")
    }

IntelliJ's light bulb offers to "Convert property getter to initializer", which changes the code to this:

override val value: String = webElement.getAttribute("value")

To me, it seems like this isn't a simple refactoring, but a significant code change. What I think is happening is:

  • In the first version, the value property is retrieved when I call value.

  • In the changed version, the value property is set immediately when the class instance is constructed, and then never changes for that class instance.

But maybe this is more like C# expression-bodied members, which use a lambda arrow => instead of braces and return but otherwise work exactly the same way.

So...which is it? When will the second version of the code initialize?

1 Answers

You are correct regarding these statements:

  • In the first version, the value property is retrieved when I call value.

  • In the changed version, the value property is set immediately when the class instance is constructed, and then never changes for that class instance.

IntelliJ's light bulb offers to "Convert property getter to initializer" because it is just an option available. Light bulb only highlights the actions you can do with a selected piece of code.

IntelliJ does not try to tell you that "property initializer" and "property getter" are equal. What it tells you is that you can convert one to the other if you wish to.

I agree that it is confusing, especially considering this quote from IntelliJ Idea documentation:

As soon as the IDE finds a way to alter your code, it displays a yellow bulb icon in the editor next to the current line. By clicking this icon, you can view intention actions available for this unit of code. Intention actions cover a wide range of situations from warnings to optimization suggestions. You can view the full list of intentions and customize them in the Settings/Preferences dialog ⌘,.

Having this in mind it could appear that your code is either can be optimized or has a warning.

The answer

When will the second version of the code initialize?

... immediately when the class instance is constructed.

You are correct.

Related