Limnic
Limnic

Reputation: 1876

Kotlin extension properties not recognized in V1.0.1

Revisiting some code from a pre-1.0.1 version of Kotlin, it appears that my extension property no longer works. In fact, it still does but I can no longer override it.

Consider this class:

class TestClass {

    override val loggerName: String
        get() = "A new name"

    fun aMethod() {
        info("test info message")
    }
}

Pre Kotlin 1.0.1 this would work if you have the following extensions:

val Any.loggerName: String
    get() = javaClass.simpleName!!

fun Any.info(message: String) {
    //...
}

loggerName would by default take the class name of the instance in question. Currently, loggerName is correctly assigned to TestClass in this case, however I cannot override it.

Is this an accidental bug or a new limitation in this new version of Kotlin? I have searched Kotlin - Extensions but found only that it should work.

Technicals:

I am testing this in IntelliJ IDEA 2016.1 with Kotlin plugin version 1.0.1-release-IJ143-32.

EDIT 1:

TestClass does not even recognize this property however when accessing an instance of TestClass (example: instanceOfTestClass.loggerName) it is recognized.

Upvotes: 1

Views: 971

Answers (2)

pRaNaY
pRaNaY

Reputation: 25312

Make sure your gradle look like below :

 apply plugin: 'kotlin-android'
...
sourceSets {
    main.java.srcDirs += 'src/main/kotlin'
}
...
dependencies {
    ...
    compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
}
...
buildscript {
    ext.kotlin_version = '1.0.0-XYZ'
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}

Replace $kotlin_version with your kotlin version.

Note: If you are using Android Studio 2.0 Preview, expect some weir behaviours in the Plugin, also in some situations it stop working, so for now suggest you to use 1.5 version as it’s working as expected.

See Configuring Android Studio with Kotlin

hope its helps you.

Upvotes: 0

yole
yole

Reputation: 97168

Overriding an extension property with a property of a class was not possible in any pre-release version of Kotlin, nor it is possible in 1.0.1. Extension properties are compiled to static methods, and code accessing the extension properties is simply calling the static method; there is no possibility to perform dynamic dispatch based on the type of the receiver.

Without the override, the extension property will work. You need to make sure that you have imported it in the place where you try to access it.

Upvotes: 3

Related Questions