How to return null in Kotlin?

Member

by wilhelm , in category: Other , a year ago

How to return null in Kotlin?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by hailie , a year ago

@wilhelm In Kotlin, you can add a question mark to the return value to specify that it may be returned null. Code as an example:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
fun getNameOrNull(name: String): String? {
    if (name != "") {
        return name
    }
    return null
}

fun main() {
 	val res = getNameOrNull("")
    
    // Output: null
    println(res)
    
    val res2 = getNameOrNull("john")
    
    // Output: john
    println(res2)
}

Member

by tina , 5 months ago

@wilhelm 

In the example above, the getNameOrNull function takes a name parameter of type String and returns a nullable String?.


Inside the function, it checks if the name is an empty string. If it is not, it returns the name. Otherwise, it explicitly returns null.


In the main function, we create two variables res and res2 to hold the return values of getNameOrNull with different inputs. The output of printing these variables will be null for an empty name and the actual name for a non-empty name.


By declaring the return type as String?, we are telling Kotlin that this function may return null, depending on the condition.