Carl
Carl

Reputation: 250

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

Upvotes: 4

Views: 3190

Answers (1)

user254948
user254948

Reputation: 1056

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")

Upvotes: 8

Related Questions