Accessing Kotlin extension functions from Java

前端 未结 9 1064
梦毁少年i
梦毁少年i 2020-11-29 21:27

Is it possible to access extension functions from Java code?

I defined the extension function in a Kotlin file.

package com.test.extensions

import c         


        
9条回答
  •  再見小時候
    2020-11-29 21:54

    As far as I can tell this isn't possible. From my reading of the extensions docs, it appears that

    public fun MyModel.bar(): Int {
        return this.name.length()
    }
    

    creates a new method with the signature

    public static int MyModelBar(MyModel obj) {
        return obj.name.length();
    }
    

    Then, Kotlin maps that function to calls of the form myModel.bar(), where if bar() isn't found in the MyModel class it looks for static methods matching the signature and naming scheme it outputs. Note that this is just an assumption from their statements about extensions being statically imported and not overriding defined methods. I haven't gotten far enough in their source to know for sure.

    So, assuming the above is true there's no way for Kotlin extensions to be called from plain old java code, as the compiler will just see an unknown method being called on an object and error out.

提交回复
热议问题