1

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()
}
0

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.