arekolek
07/04/2019, 12:24 PMinline fun Foo.notMyFunction(block: Bar.() -> Unit) {
bar.apply(block)
}
inline fun <R> Foo.myFunction(block: (Bar) -> R): R {
notMyFunction {
return let(block)
}
error("")
}
is there any reasonable way to implement myFunction
given notMyFunction
?Marc Knaup
07/04/2019, 12:26 PMnotMyFunction
. But you can't use inline
then.Dico
07/04/2019, 2:59 PMreturn block()
insteas of let(block)?arekolek
07/04/2019, 6:57 PMlet(block)
, block(this)
, whatever, but mainly I’m wondering if it’s possible to get some value out of there without that error("")
at the end
reason was: using a function with similar signature in class initialization - can’t initialize properties inside the lambda, but could assign the property with result of myFunction
Marc Knaup
07/04/2019, 7:38 PMnotMyFunction
invocation never returns you have to tell it that its lambda is called exactly once.
@UseExperimental(ExperimentalContracts::class)
inline fun Foo.notMyFunction(block: Bar.() -> Unit) {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
bar.apply(block)
}
inline fun <R> Foo.myFunction(block: (Bar) -> R): R {
notMyFunction {
return let(block)
}
}
arekolek
07/04/2019, 7:54 PMnotMyFunction
is not mine, so I’d have to request that feature. Still, even if it was added, would it be possible to get the value out of there, without defining myFunction
? Assuming Bar
has a getBoolean
function:
class Baz(foo: Foo) {
val spam: Boolean = foo.notMyFunction {
// some magic to make apply work like let and return:
getBoolean("spam")
}
}
Marc Knaup
07/04/2019, 7:57 PMclass Baz(foo: Foo) {
val spam = with(foo) { lateinit var magic: String; notMyFunction { magic = "spam" }; magic }
}
karelpeeters
07/05/2019, 8:05 AM@UseExperimental(kotlin.contracts.ExperimentalContracts::class)
inline fun Foo.notMyFunction(block: Bar.() -> Unit) {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
bar.apply(block)
}
fun main() {
val foo = Foo()
val spam: Boolean
foo.notMyFunction {
spam = getBoolean("spam")
}
println(spam)
}