Reputation: 513
How to emulate the same behaviour using lambdas kotlin.
Java Code:
public interface OnClickListener{
public void onClick();
}
public class Sample {
OnclickListener mOnclickListener;
public void setOnclickListener(OnclickListener l){
if(l!=null)
mOnclickListener =l;
}
public void performClick()
{
mOnclickListener.onClick(5);
}
}
public class SampleImpl{
Sample sample=new Sample();
sample.setOnClickListener(new OnClickListner(){ onClick{}});
sample.performClick();
}
As per kotlin, function receives parameter of interface with single method can represent in lambda, i am trying...
Kotlin code :
var sample= Sample();
sample.setOnClickListener({Int -> println("action performed") })
sample.performClick(); //will call this method whenever needed.
class Sample {
var click=null;
fun setOnClickListener(onClick : (Int)->Unit){
click= onClick // trying to assign and want to use it in another
funciton. I know it is wrong, how to achieve
this.
}
fun performClick()
{
click(5)
}
}
Is there any alternative to achieve this?
Upvotes: 1
Views: 115
Reputation: 321
I know it already answered, but if you want to stick with null
declaration of click
variable, you can write it like:
class Sample {
var click: ((Int)->Unit)? = null
fun setOnClickListener(onClick : (Int)->Unit) {
click = onClick
}
fun performClick() {
click?.invoke(5)
}
}
Hope it can help anyone
Upvotes: 0
Reputation: 3478
Alterantively you can try this:
interface OnClickListener {
fun onClick()
}
inner class Sample {
internal var mOnclickListener: OnClickListener
fun setOnclickListener(l: OnClickListener?) {
if (l != null)
mOnclickListener = l
}
fun performClick() {
mOnclickListener.onClick(5)
}
}
inner class SampleImpl internal constructor() {
internal var sample = Sample()
init {
onClick
run { }
}
}
Upvotes: 0
Reputation: 58437
The compiler has no way of inferring a type of (Int) -> Unit
from var click = null
.
You can change the declaration to something like var click : (Int) -> Unit = {}
. This explicitly states the type, and uses a non-nullable type so as not to complicate performClick
.
Upvotes: 4