Hi guys one question, I want to have a variable th...
# announcements
o
Hi guys one question, I want to have a variable that represent Any function. meaning that function can have from 0 to N different params, is that possible?
r
If you don't mind my asking, how would that be useful?
o
So what I would like to have is a hashmap<String, AnyLambda>, and depending on the key just call the lambda associated
r
How would you call it?
o
thats the question hahaha
so if the map is like
var x: Map<String,()->Unit
r
(
Function
is the super type of all functions in Kotlin, but it can't be invoked in any way.)
o
its simple
x[key]?.invoke()
, but my functions can have one or two params, I’m trying to avoid having a when
c
You’d have to know the params to pass to each function in that map. A better approach would be to pass a function factory into that map. Calling the factory function with no params, which knows how to call the other functions
r
How can you invoke it without parameters?
o
@Casey Brooks do you have any example of it ?
c
Copy code
val x = mutableMapOf<String, ()->Unit>()

fun addCallback(key: String, cb: ()->Unit) {
    x[key] = cb
}

fun elsewhere() {

    addCallback("some_key") {
        callOtherMethodWithLotsOfParams(param1, param2, ...)
    }
}
o
I will try it, thanks
@Casey Brooks @Ruckus thanks for your comments, so it works, I just test it and works like magic
Copy code
class X  {
    val map = HashMap<String, ()-> Unit>()

    fun addKey(key:String, lambda: ()-> Unit){
        map[key] = lambda
    }

}

class Y(val param1: String, val  param2: Int){

    fun myLongFuction(){
        print("doing some big work with $param1 and $param2")
    }
}

class Z(){

    fun myLongFuction(){
        print("I do not have parameters")
    }
}

class CLL {

    @Test
    fun cll(){
        val x = X()
        x.addKey("1"){
            Y("Oscar", 1).myLongFuction()
        }

        x.addKey("2"){
            Z().myLongFuction()
        }

        x.map["1"]?.invoke()
        x.map["2"]?.invoke()
    }
}
🎉 2