Kotlin Data Classes and NULL Types

I'm new to Kotlin, and I don't know why the compiler complains about this code:

data class Test(var data : String = "data") fun test(){ var test: Test? = Test("") var size = test?.data.length } 

The compiler complains about test?.data.length , it says what I should do: test?.data?.length . But the data variable is String , not String? so I don’t understand why I need to put ? when I want to check the length.

+7
android kotlin data-class
source share
2 answers

The expression test?.data.length equivalent to (test?.data).length , and the test?.data (test?.data).length part is NULL: it is either test.data or null . Therefore, getting length not practical, but instead you should use the safe call operator again: test?.data?.length .

Infidelity spreads throughout the call chain: you need to write these chains as a?.b?.c?.d?.e (which again is equivalent to (((a?.b)?.c)?.d)?.e ), because if one of the left parts is zero, the rest of the calls cannot be executed as if the value were not zero.

+10
source share

If you do not want to use a safe call before each unimaginable component of the call chain, you can get the result of the first safe call to a new variable with standard run or let extension functions

 // `this` is non-nullable `Test` inside lambda val size = test?.run { data.length } // or: `it` is non-nullable `Test` inside lambda val size = test?.let { it.data.length } 

Note that size may still be an invalid Int? here.

+3
source share

All Articles