i am sorry if my question is stupid, but i realize that my mind still seems to be suck in the strictly object orientated java way of thinking and don’t know how to solve my problem with kotlin, although i already read the documentation of kotlin and followed some tutorials.
right now i dont know how to add a custom listener to a class. here is an example of how i would do it with java.
public class Test {
private OnActionListener onActionListenerListener;
public Test(OnActionListener onActionListenerListener){
this.onActionListenerListener = onActionListenerListener;
}
public interface OnActionListener {
void onAction();
}
public void doAction(){
this.onActionListenerListener.onAction();
}
}
class Test2{
public Test2(){
Test test = new Test(new Test.OnActionListener() {
public void onAction() {
// do something
}
});
test.doAction();
}
}
as far as i understand kotlin does not need objects for that, so there must be a way how to store a function and set it from outside. how do i do that?
fun main(args: Array<String>) {
val test = Test {
// do something
println("actually do something")
}
test.doAction()
}
class Test(private val onActionListenerListener: () -> Unit) {
fun doAction() {
onActionListenerListener()
}
}
The big difference is with the () -> Unit declaration.Which is just a general purpose interface (Function) since there is probably no need to define a specific one.
thanks, but i already did something like this, and it worked fine; i was able to use the function passed as argument for my purpose, but i wonder if its possible to store this function somewhere like a property. or is this a wrong way of thinking?.
what if i dont pass this function in the constructor but want to add it later if its necessary?
finally i was able to answer my question on my own. this is the kotlin code i was searching for.
class Test {
var onAction = fun(x: Int, y: Int): Int = null!!
fun doAction() {
onAction(1, 2)
}
}
class Test2{
fun testFun(){
var test = Test()
test.onAction = fun(x, y): Int {
return x + y
}
}
}
Assuming returning an Int from the function is a typo as I do not see this in the Java code, I would assign a no-operation function to the variable so you do not risk a null pointer exception:
var onAction = { x: Int, y: Int -> }
Unless, of course, it is an error to not have initialized onAction.
@jstuyts: your example does not work when i try to assign a function to it. i also did not understand why you assume that Int is a typo. anyway the solution of @dalewking works and compiles perfectly fine, so i consider my question as answered.
sorry, i forgott that i wrote example java code at the beginning, i understand now and it also works.actually i like your solution even more as i dont have to care if this function is set or not, and never get any exception.