Kory
Kory

Reputation: 31

Is it better to use a lambda if a variable is not always needed?

I have a class that loads no matter what but only needs a parameter if clicked. Is it better to always pass in the parameter to the class or pass a lambda and invoke that when clicked?

example:

class ItemViewModel(item: ProductItem,
                    private val index: Int,
                    private val title: String?){
    fun onItemClick() = foo(title)
}

or

class ItemViewModel(item: ProductItem,
                    private val index: Int,
                    private val getTitle: () -> String?){
    fun onItemClick() = foo(getTitle)

}

Upvotes: 0

Views: 74

Answers (1)

TooManyEduardos
TooManyEduardos

Reputation: 4434

Your question, and code sample, are several things in one.

  1. Is it better to use a lambda if a variable is not always needed? If you're using Kotlin (which you are in your example) then your parameter can be set as optional (which you're doing) by marking it with a ?. This means that the caller of this function can pass null as a value, and the function should work as expected.

Now, if you ahead of time know that clients will pass null (or some value), and you don't care if they do, and you want to make it easier for clients to call this function and not have to pass a parameter, you can mark your parameter as ? = null. For example:

class ItemViewModel(item: ProductItem,
                    private val index: Int,
                    private val title: String? = null){
    fun onItemClick() = foo(title)
}

Keep in mind though that your function foo must also accept a possible null value for this example.

Or:

class ItemViewModel(item: ProductItem,
                    private val index: Int,
                    private val title: String? = "Default title"){
    fun onItemClick() = foo(title)
}

This means that you can now call this as ItemViewModel(ProductionItem.SomeItem, 1). A third parameter is not needed (but it is still accepted if you do pass one).

  1. Lambda parameters are often only used to say that the parameter you're requiring should be a callback. In other words, you would pass a lambda for something like "onComplete", and let the client handle the response of your foo function.

  2. Conventionally, you wouldn't pass a parameter (that is not a callback) as a lambda. Sure, you CAN do it, but it's a very strange way of doing it and nobody would understand why you did it.

  3. As mentioned in a comment, lambdas are often much more memory consuming than variables (unless your variable is a serialized object, like an image or something like that)

Upvotes: 1

Related Questions