Kotlin's crossinline keyword -


i have read this question have more fundamental question regarding crossinline keyword. i'm not sure problem solving , how solves it.

from the kotlin docs,

note inline functions may call lambdas passed them parameters not directly function body, execution context, such local object or nested function. in such cases, non-local control flow not allowed in lambdas. to indicate that, lambda parameter needs marked crossinline modifier:

[emphasis added]

this statement ambiguous me. first, having trouble picturing meant "such cases". have general idea of issue can't come example of it.

second, phrase "to indicate that," can read multiple ways. indicate what? a particular case not allowed? is allowed? non-local control flow in given function definition (or not) allowed?

in short, have trouble figuring out context using is, using communicates clients, , expected results of applying keyword are.

first, having trouble picturing meant "such cases". have general idea of issue can't come example of it.

here's example:

interface someinterface {     fun somefunction(): unit }  inline fun someinterfaceby(f: () -> unit): someinterface {      return object : someinterface {         override fun somefunction() = f()          //                            ^^^         // error: can't inline 'f' here: may contain non-local returns.          // add 'crossinline' modifier parameter declaration 'f'.     } } 

here, function passed someinterfaceby { ... } inlined inside anonymous class implementing someinterface. compilation of each call-site of someinterfaceby produces new class different implementation of somefunction().

to see go wrong, consider call of someinterfaceby { ... }:

fun foo() {     val = someinterfaceby { return }     // `i` } 

inside inline lambda, return non-local , means return foo. since lambda not called , leaks object i, return foo may absolutely meaningless: if i.somefunction() (and lambda) called after foo has returned or in different thread?

generically, 'such cases' means inline functions call functional parameters not in own bodies (effectively, i.e. taking other inline functions account) inside other functions declare, in non-inline lambdas , anonymous objects.


second, phrase "to indicate that," can read multiple ways. indicate what? particular case not allowed? allowed? non-local control flow in given function definition (or not) allowed?

this how problem described above fixed in kotlin language design: whenever inline function intends inline functional parameter somewhere not called in-place stored , called later, parameter of inline function should marked crossinline, indicating non-local control flow not allowed in lambdas passed here.


Comments

Popular posts from this blog

What is happening when Matlab is starting a "parallel pool"? -

angular - DownloadURL return null in below code -

php - Cannot override Laravel Spark authentication with own implementation -