What is the idiomatic way to deal with null able values, referencing or converting them?
What is the idiomatic way to deal with null able values, referencing or converting them?
Here is an idiomatic way to deal with nullable values in Kotlin:
The safe call operator ?. is used to safely access properties or call methods on a nullable reference. If the reference is not null, the operation is performed, otherwise null is returned. For example:
val length = person?.name?.length()
This will return the length of the name string if person and person.name are not null, otherwise it will return null.
The Elvis operator ?: is used to provide a default value if a nullable expression evaluates to null. For example:
val name = person?.name ?: "Anonymous"
This will assign the value of person.name to name if it is not null, otherwise it will assign the default value "Anonymous".
The non-null assertion !! is used to assert that a nullable expression is not null. If the expression is null, it will throw a NullPointerException. For example:
middle
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào