How Java calls kotlin extension methods

How Java calls kotlin extension methods … here is a solution to the problem.

How Java calls kotlin extension methods

I wrote an extension method in kotlin

package com.zhongan.zachat.extention

import android.content.Context
import android.widget.Toast

 * Created by Carl on 2016/12/1.

fun Context.toastLong(msg:String) = Toast.makeText(this,msg,Toast.LENGTH_LONG).show()

fun Context.toastshort(msg:String) = Toast.makeText(this,msg,Toast.LENGTH_SHORT).show()

When I call toastLong("test") in the kotlin activity
No problem.
But in the java actvity IDE it says that this method cannot be found.

How to call the Kotlin extension method in Java code


Based on this page

Extensions do not actually modify classes they extend.

It is important to note that extensions cannot be called from an object class because the original class is still the same. (So Context doesn’t magically have extra functionality, so it can’t be called in Java using Context.functionName.)

You should be able to call it in the following way:


For example, if the file name is kotlinFile.kt:


Related Problems and Solutions