Using parameter passed in a passed function ;)


#1

Hi all, I have following:

fun <T> checkCondition(fn: MyMatcher.(arg: T) -> Unit)  { 
    val matcher = MyMatcher()
    matcher.fn(arg)
    println("check condition call")
}

Unfortunately arg is an unresolved reference in fun body ;/, however, when I did:

fun <T> checkCondition(fn: MyMatcher.(arg: T) -> Unit) = { arg: T ->
    val matcher = MyMatcher()
    matcher.fn(arg)
    println("check condition call")
}

but now the only way I can make call to this function is by:

checkCondition<Int> ({ isGreaterThanZero(myInt) })(otherIgnoredInFunBodyInt)

where otherIgnoredInFunBodyInt is not considered in my function body, I get proper results for myInt

simple:
checkCondition<Int> ({ isGreaterThanZero(myInt) }) is called never.

Thanks in advance for resolving my misunderstandings :slight_smile:


#2

You are passing lambda with argument to checkCondition, but no actual argument.
Equivalent code with less eycandy looks like this

fun <T> checkCondition(fn: (matcher:MyMatcher, arg: T) -> Unit)  { 
    val matcher = MyMatcher()
    fn(matcher, arg)  // error: where does arg come from????
    println("check condition call")
}

#3

There is no partial application and currying in kotlin btw.


#4

So it won’t work that way, is that a conclusion ?


#5

You can make it work by implementing partial application manually.

fun <T> checkCondition(fn: MyMatcher.(arg: T) -> Unit) :(arg: T)->Unit {  
    val matcher = MyMatcher()
    return {
        matcher.fn(it)
        println("check condition call")
    }
}

Also = sign is misguiding. Kotlin has different syntax to scala


#6

Look at funKTional for partials and currying