How to return boolean value from a function in Kotlin

13,163

This is about nullability.  The Kotlin compiler keeps track of whether each value could be null or not, and prevents you from doing things that would be unsafe.

The code in this question has one particular nullability issue.  (It also has some confusion, including two references to key before it's set.  I'll assume those should be siteId.)

The issue is what happens when the abcEnabled map doesn't contain the requested key.  If the key is present, then the […] operator will return the corresponding Boolean value; but if the key is not present (which could happen if the map doesn't contain a "default" key), it returns null.  However, the variable you're trying to assign it to is of type Boolean, which doesn't allow nulls.  That's why the compiler complains.

So you'll have to decide what you want to happen if the map contains no "default" key.  (Or find a way to ensure it always does; but that's a lot harder, especially if the method could be called before the object is fully initialised, or while another thread is setting or updating the map.  So it's much safer to handle the case gracefully.)

If you want to return false in that case, the code could boil down to:

fun getabcEnabledValue(siteId: String?): Boolean {
    val key: String? = if (abcEnabled.containsKey(siteId)) siteId else "default"
    return abcEnabled[key] ?: false
}

or even (for better thread-safety as well as brevity and clarity):

fun getabcEnabledValue(siteId: String?)
    = abcEnabled[siteId] ?: abcEnabled["default"] ?: false

Or if you want to return null in that case, simply declare the function as returning Boolean? (which allows null) — or leave off the ?: false in the last example.

(Also, as a matter of style, I'm not sure why you've made abcEnabled a private property and then added your own setter.  Is it really necessary to hide the getter?  If not, a public property would be simpler.  And it's probably worth making the capitalisation of abc in the method names consistent.)

Share:
13,163

Related videos on Youtube

umesh
Author by

umesh

Updated on June 04, 2022

Comments

  • umesh
    umesh almost 2 years

    I am new to kotlin. I am reading a key and value from properties file, in a kotlin program. But I don't know how to directly return the value of a key. Please find the application.yml and abc.class(this is a kotlin class) below.

    application.yml

    abcconfig:
      isabcEnabled:
        default: false
        xyz: true
        def: true
    

    abc.class

    import org.springframework.boot.context.properties.ConfigurationProperties
    import org.springframework.stereotype.Component
    
    @Component
    @ConfigurationProperties(prefix = "abcconfig")
    class AbcConfig {
    
        private var abcEnabled: Map<String, Boolean> = mutableMapOf()
    
        fun getabcEnabledValue(siteId: String?): Boolean {
    
            val abc: Boolean
            val key: String? = if (abcEnabled.containsKey(key)) key else "default"
    
            abc = abcEnabled[key]
            return abc
        }
    
        fun setAbcEnabled(abcEnabled: Map<String, Boolean>) {
            this.abcEnabled = abcEnabled
        }
    
    }
    
    • JB Nizet
      JB Nizet about 5 years
      What is your question?
    • umesh
      umesh about 5 years
      When i am trying to assign value to abc using abcEnabled[key], compiler is giving an error of type conversion.
    • JB Nizet
      JB Nizet about 5 years
      The type of your Map is Map<String, Boolean>. So its keys are of type String. But your key variable is of type String?. It should be String. Same for siteId. Read kotlinlang.org/docs/reference/null-safety.html
    • Anthon
      Anthon about 5 years
      Any valid reason not to follow the official recommended file extension for YAML documents (Which has been .yaml since 2006)