Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Correct usage of return if in Kotlin

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading