Default value for parameter in multiple lambda input function

I’m trying to be able to run this code:

class test {

    fun test() {
        MinOreo { print("Oreo and above")}
        MinOreo ({print("Oreo and above")},{print("Below Oreo")})
    }
}

For this I’ve specified this function:

fun <T> T.MinOreo(block: T.() -> Unit, blockElse: T.() -> Unit = {}) = doForMin(block, blockElse, Api.OREO)

It doesn’t work. The first “MinOreo” block above fails to compile:

 No value passed for parameter 'block'

If I add this it then starts to work:

fun <T> T.MinOreo(block: T.() -> Unit) = doForMin(block, {}, Api.OREO)

Shouldn’t it work with the default parameter version of the function alone?

Thanks in advance!

When you omit the parenthesis, the lambda should be for the last parameter of the function.

So when you call MinOreo {...} you are actually calling MinOreo(no value here, {...}).
If you call MinOreo({...}) it should work in this case.

1 Like

Oh, I see! So using

fun <T> T.MinOreo(blockElse: T.() -> Unit = {}, block: T.() -> Unit) = doForMin(block, blockElse, Api.OREO)

will work! :slight_smile: Was not aware of that particularity. Thank you very much!