Correct usage of return if in Kotlin

Advertisements

So in Kotlin you can write the below function in two ways:

fun getProduct(id: Int): Product? {
    if (id < 1 ) return null
    return productProvider.getProduct(id) /// Assuming getProduct NEVER fails
}

Or as below:

fun getProduct(id: Int) = if (id > 0 ){
   productProvider.getProduct(id) /// Assuming getProduct NEVER fails
}else {
    null
}

I am being suggested to always use the latter, as is the proper way.
Can someone point me in the right direction on this? Why is the second syntax better?

I can guess that performance wise they are exactly the same and ( IMO ) I do not find the second one more readable at all.

>Solution :

It is not more correct or better-performing. It is a style choice.

You do have the option of including the return type to make the second one more readable:

fun getProduct(id: Int): Product? = if (id > 0 ) {
    productProvider.getProduct(id)
} else {
    null
}

A when expression could also help here.

Leave a ReplyCancel reply