I just learned that when defining a higher order f...
# getting-started
u
I just learned that when defining a higher order function, the parameters for the secondary functions can be declared nullable to make supplying them every time optional.
Copy code
fun trickOrTreat(isTrick: Boolean, extraTreat: ((Int) -> String)?): () -> Unit {
    if (isTrick) {
        return trick
    } else {
        if (extraTreat != null) {
            println(extraTreat(5))
        }
        return treat
    }
}
Is this actually common or good practice?
y
It prevents
inline
ing, for one, which is annoying. Having a default lambda is probably the better option.
joinToString
does the same thing that you do there, and it's very annoying
u
That's very helpful, thank you!
y
You can also do:
Copy code
fun trickOrTreat(isTrick: Boolean): () -> Unit = if (isTrick) trick else treat
fun trickOrTreat(isTrick: Boolean, extraTreat: (Int) -> String): () -> Unit = if (isTrick) trick else {
  println(extraTreat(5))
  treat
}
u
Ah, so you're saying that, like variables, I can actually define function bodies based on the results of a conditional statement?
✔️ 1
Wait this is also an example of function overloading right? Is that what you actually wanted me to see?
✔️ 1
y
Yes the overloading was the point. I wrote it as a single-expression function out of laziness lol!
u
Haha! Love it. Thank you, sir!
n
I've used it a handful of times in some of my DSLs
l
Why not just do something like:
Copy code
fun trickOrTreat(extraTreat: (Int)->String = {trick}): String {
    return extraTreat(1234)
}
Then you can either call it without arguments, thus getting the default:
trickOrTreat()
, or you cal call it with a function, to get that result:
trickOrTreat { "abc" }