Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 564 Vote(s) - 3.41 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Kotlin read only property with and without getter

#1
Are these equivalent?

*
`val foo = someFooReturningFunction()`

* ```val foo get() = someFooReturningFunction()```

The way I understood the documentation they were, but in my own testing they are not.

With the *get()* `someFooReturningFunction()` is evaluated each time the property is accessed, without it is only evaluated once.
Reply

#2
They are not equivalent. The custom getter is indeed evaluated on each property access, similarly to a normal function, while a `val` property with no custom accessors is only evaluated once on initialization (and is actually stored in a `final` field on JVM platform).

Here are at least a few more differences:

* The control flow analysis and nullability inference takes it into account if a property has a custom getter (or is `open` and thus might be overridden with a custom getter), because there's no guarantee that the property returns the same value on successive calls:

if (someObject.defaultGetterProperty != null) {
someObject.defaultGetterProperty.let { println(it) } // OK
}

<sup></sup>

if (someObject.propertyWithCustomGetter != null) {
someObject.propertyWithCustomGetter { println(it) } // Error: cannot smart-cast
}

* When a property is `private`, if it has no custom getter then the getter is not generated at all and the backing field is accessed directly. This, however, is an implementation detail and not something to rely on.
Reply

#3
No. In addition to @hotkey's reasons, here's a simple demonstration using mutable properties showing when they're definitely not equivalent. TLDR: if your property is calculated using a mutable property, always use a custom getter over an initializer.

data class Calculation(val value1: Int, var value2: Int) {
val sum: Int = value1 + value2
val sumWithGetter: Int
get() = value1 + value2
}

val calculation = Calculation(1, 2)
println(calculation.sumWithGetter) // prints 3
println(calculation.sum) // prints 3

calculation.value2 = 0
println(calculation.sumWithGetter) // prints 1 (correct)
println(calculation.sum) // prints 3!
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through