About passing lambda as property

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
    }
}

When should I use case 1or case 2 ?

({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.

And please do use syntax highlight function.

@darksnake
Thank you for the reply.
I am confused that if I pass lambda as

private val foo: Boolean by lazy {
        // Here is logic that return true or false
}

Does it make performance better than pass actual value ?

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.

1 Like

Thank you @darksnake !!!