Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java how to call kotlin extension method

I use kotlin write a extension method

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 in kotlin activity call toastLong("test") is ok.
but In java actvity IDE say can not found this method.

how Can I call kotlin extension method in java code

like image 717
Carl Avatar asked Feb 06 '23 14:02

Carl


1 Answers

Based on this page

Extensions do not actually modify classes they extend.

It should be noted that the extension can not be called from the object class, since the original class is still the same. (So Context does not magically have a extra function, hence it can't be called using Context.functionName in Java)

You should be able to call it using:

com.zhongan.zachat.extention.<fileName>.toastLong(ctx,"string")

e.g. if the file is called kotlinFile.kt:

com.zhongan.zachat.extention.KotlinFileKt.toastLong(ctx,"string")
like image 126
user254948 Avatar answered Feb 08 '23 04:02

user254948