Home > Blockchain >  What is the difference between String? and String! in Kotlin
What is the difference between String? and String! in Kotlin

Time:05-10

I want to know the difference between String? and String! in Kotlin. I search on kotlinlang.org but did not find any information.

CodePudding user response:

Kotlin's type system differentiates between enter image description here

fun testStringTypes() {
    val someStringFromJava = PlatformTypeTest().returnSomeStringCouldBeNull()
    someStringFromJav
}

enter image description here

As we can see from above two screenshots, IDE is reminding us this String from Java can be null.

And for String!, we can access it in different ways:

fun main() {
    val someStringFromJava = PlatformTypeTest().returnSomeStringCouldBeNull()
    var lenOfString = someStringFromJava?.length ?: 0
//    lenOfString = someStringFromJava.length // NullPointerException
//    lenOfString = someStringFromJava!!.length // NullPointerException
    println(lenOfString)
}

With code snippet above, it works fine with var lenOfString = someStringFromJava?.length ?: 0, but the other two ways will cause NPE, as explained at above.

  • Related