How to deal with database null return according Kotlin Null Safety feature

I am very new to Kotlin programming language. Null safety is a very interesting feature. But in real life programming where I used to use null, how to deal with those ? Like following example :

@Service
open class OrganizationService(val orgRepo: OrganizationRepository) {   
    @Transactional
    open fun findByName(name: String): Organization? {
        return orgRepo.findByName(name)
    }
}

This is a very simple spring service layer, where I am retrieving data using Spring Data JPA. It is very common to check null whether the data is in DB or not. So I need to put ? in the return type to tell compiler that return type Organization could be null. Then I have to carry out this ? in everywhere I am going to use this object. Literary I need to check if(org != null)... .Could Kotlin Null Safety help out this type of scenario ?

Thanks. :slight_smile:

Since it could happen that a certain organization doesn’t exist, you have to make this explicit and mark the types with ?. Otherwise you would get NullPointerExceptions as in Java.

Side Note: If you really just delegate to the underlying repo you could use it directly without a service (but maybe your example is just simplified).

You shouldn’t have to add the ? everywhere. Only the direct caller of findByName needs to do that check. The code branch that is executed when the organisation is not null no longer needs the ?.

Here is an example:

findByName("acme")?.let { org -> // Type of 'org': Organization
    printOrg(org)
}

// No '?' here
fun printOrg(org: Organization) { ... }
1 Like

Various approaches of dealing with nulls are also covered in this SO topic: In Kotlin, what is the idiomatic way to deal with nullable values, referencing or converting them - Stack Overflow

1 Like