I am trying to create an extension as a property and I experimented with an extension function as well, below an example for BigDecimal
:
val BigDecimal.HUNDRED: BigDecimal
get() = TEN.multiply(TEN)
fun BigDecimal.HUNDRED_ONE(): BigDecimal {
return TEN.multiply(TEN)
}
It seems that Kotlin recognizes neither HUNDRED
nor HUNDRED_ONE()
. I am using Kotlin version 1.5.21
.
Am I doing anything wrong on Kotlin version 1.5.21
that doesn't work correctly?
I have used this functionality before for lists. For instance:
fun <T> toList(list: List<T>?): List<T> {
return list ?: listOf()
}
I assume you wanted to use it like this:
val value = BigDecimal.HUNDRED
As far as I know, this is not possible in Kotlin right now. Extensions work on instances, so they're more like instance members, not static members. With your above code this will work: BigDecimal(0).HUNDRED
.
I believe there is only one situation when it is possible to provide "static" extensions. If class has a companion (so it is Kotlin class) then we can add extensions to this companion. But this is not at all applicable to BigDecimal
or any other Java class.