Why are nullable function parameters not allowed o...
# announcements
k
Why are nullable function parameters not allowed on an inline function? Eg this gives an error:
Copy code
inline fun foo(block: (() -> Unit)?) {
    block?.invoke()
}
Inline parameter [...] must not be nullable. Add 'noinline' modifier to the parameter declaration or make its type not nullable
Why? Would there be a problem compiling something like that? I can't imagine why. Interestingly you can suppress this,
Copy code
@Suppress("NULLABLE_INLINE_PARAMETER")
but that does't actually inline the lambda, and the IDE doesn't suggest that.
a
What would you want this to do and why?
r
Not really sure what you’re trying to accomplish here, but I think you could probably just default
block
to
{}
. That’d remove the need for nullability altogether
k
My use case was just an optional function parameter, but
{}
covers that nicely. Thanks!
👍 1
I can imagine there being usecases for actual null lambdas though, I'm still curious why they're not supported.
r
I guess I don’t know where I would prefer to pass in null when I could just pass in nothing. Either way, don’t you just have to mark the lambda as
noinline
? The function that takes the lambda argument can be inlined, but the generated lambda can’t be inlined if it’s null, right? this seems to work:``` private inline fun foo(noinline bar: (() -> Unit)?) { bar?.invoke() } ```
k
Yeah that works but of course it defeats the purpose of
inline
entirely. Why is there a problem with inlining a nullable lamµbda in the first place?
r
I thought the purpose of
inline
was to place the contents of a method at the call site at compile time. Doesn’t this still accomplish that? It just doesn’t also erase the argument’s signature. So net method change is +1 rather than 0 or +2. Not exactly what we’re wanting, but the purpose isn’t entirely defeated. As to why, I’ll have to defer to someone with more knowledge.
k
Lambdas for non-inline functions get compiled to anonymous classes with an invoke method. Every time the function is called a new instance of that anonymous class is created. The purpose of
inline
is mainly to avoid that overhead, not so much the function call itself which the JVM can inline itself just fine. InteliJ even has a warning when you're unnecessarily using inline, try eg.
inline fun test() {}
.
💡 1