Rohit Parmar
Rohit Parmar

Reputation: 397

Extensions in Kotlin

I want to use extensions for variables and method for my custom class. I am trying below code but getting error

Local extension properties are not allowed

val Double.km: Double get() = this * 1000
val Double.m: Double get() = this
val Double.cm: Double get() = this / 100
val Double.mm: Double get() = this / 1000
val Double.ft: Double get() = this / 3.28084

val oneInch = 25.4.mm
println("One inch is $oneInch meters")
// prints "One inch is 0.0254 meters"
val threeFeet = 3.0.ft
println("Three feet is $threeFeet meters")
// prints "Three feet is 0.914399970739201 meters"

How to use extensions? Can we use extensions in interface?

Upvotes: 0

Views: 2792

Answers (1)

tynn
tynn

Reputation: 39843

You have to move these declarations from the function body to the class body. Like the error states, it's not allowed to define extension properties locally, while local extension methods are ok.

So in your case you could do:

class MainClass {
    val Double.km: Double get() = this * 1000
    val Double.m: Double get() = this
    val Double.cm: Double get() = this / 100
    val Double.mm: Double get() = this / 1000
    val Double.ft: Double get() = this / 3.28084

    fun run() {
        val oneInch = 25.4.mm
        println("One inch is $oneInch meters")
    }
}

You can use the extension properties from within your MainClass, while outside usage is not possible.

Upvotes: 5

Related Questions