Tgo1014
11/10/2023, 9:36 AMclass A : () -> String {
override fun invoke() = "A"
}
class B {
operator fun invoke() = "B"
}
A()()
B()()
Sam
11/10/2023, 9:41 AMA
can be assigned directly to () -> String
but B
can't:
fun foo(bar: () -> String) = bar()
foo(A()) // ✅
foo(A()::invoke) // ✅
foo(B()) // ❌
foo(B()::invoke) // ✅
Tgo1014
11/10/2023, 9:46 AMinstance()
) it doesn’t make any difference.ephemient
11/10/2023, 9:52 AM{ "C" }()
(fun() = "D")()
run {}
if you just want a temporary scopefun makeALambda(arg: String) = { "A: $arg" }
than to write a class
with override fun invoke()
, although you do need a real class (or anonymous object) if you need to make the lambda self-referentialTgo1014
11/10/2023, 9:58 AMephemient
11/10/2023, 10:00 AM{ a: Int, b: Int -> "($a, $b)" }
(fun(a: Int, b: Int): String = "($a, $b)")
(fun(a: Int, b: Int): String {
return "($a, $b)"
})
are equivalentYoussef Shoaib [MOD]
11/10/2023, 12:07 PMyou do need a real class (or anonymous object) if you need to make the lambda self-referentialWell...
fun main() {
val factorial = makeFactorialStartingFrom(1)
println(factorial(5))
}
fun makeFactorialStartingFrom(start: Int): (Int) -> Int = fix { fact, int ->
if(int == 0) start else int * fact(int - 1)
}
fun <T, R> fix(f: ((T) -> R, T) -> R): (T) -> R = { f(fix(f), it) }
I think theoretically lambdas can do everything that classes can, except participate in class or interface hierarchies obviously.ephemient
11/10/2023, 4:20 PMval f = fix { f, _ ->
unregisterCallback(f)
}
registerCallback(f)
doesn't workYoussef Shoaib [MOD]
11/11/2023, 5:36 AMfun <T, R> fix(f: ((T) -> R, T) -> R): (T) -> R {
lateinit var fixed: (T) -> R
fixed = { f(fixed, it) }
return fixed
}
ephemient
11/11/2023, 6:04 AMfun <T, R> fix(f: ((T) -> R, T) -> R): (T) -> R = object : (T) -> R {
override fun invoke(it: T): R = f(this, it)
}
or by just doing that directly instead of using a fixed-point combinator, we're not programming in lambda calculus