I am confusing about merit of writing code as following 2 case:
class TestA {
private val foo: Boolean by lazy {
// Here is logic that return true or false
}
Case 1:
fun main() {
TestB({foo})
}
Case 2:
fun main() {
TestB(foo)
}
}
Case 1:
class TestB(private val isFoo: () -> Boolean ) {
fun checkFoo(): Boolean {
return isFoo.invoke()
}
}
Case 2:
class TestB(private val isFoo: Boolean ) {
fun checkFoo(): Boolean {
return isFoo
}
}
({foo}) and (foo) constructs do principally different things. First uses lambda that returns the function itself, and the second one uses the function that returns lambda result.
Do not think about performance when you do not know language well enough. Even better, do not think about performance at all unless you really need it. Lazy delegate just initializes value on first use and stores it. If you need to get value only once, it does not make sense to have a lazy value, you can just pass lambda directly. Everything else strongly depends on your particular case. Your Case 1 makes sense only if calculation of isFoo is heavy and is not guaranteed to take place.
I think that the general recommendation for beginners without FP experience is not to use function-values unless you understand what you are doing.