103 lines
2.5 KiB
Plaintext
103 lines
2.5 KiB
Plaintext
== Why is this an issue?
|
|
|
|
In Kotlin, nullability is a part of the type system. This means that all types could be used in 2 ways. `T` - as non-nullable and `T?` as nullable. When you want to access properties or instance methods of a nullable type, you need to handle the potential null value. However, while accessing a non-nullable type, you don't need to test nullability as the compiler knows that the value can never be `null`. So all the nullability checks on the non-nullable types are considered code smells.
|
|
|
|
Here is an example of non-nullable variable. `s` is of a type `String` and cannot be `null`.
|
|
|
|
[source, kotlin]
|
|
----
|
|
val s: String = ""
|
|
----
|
|
|
|
Here is an example of nullable variable. Nullable variables are declared by using the `?`.
|
|
|
|
[source, kotlin]
|
|
----
|
|
val s: String? = null
|
|
----
|
|
|
|
|
|
== How to fix it
|
|
|
|
Avoid using null checks on non-nullable variables.
|
|
|
|
=== Code examples
|
|
|
|
If your variable type is non-nullable, any null checks are redundant. For example, `if (s == null) {}`, `requireNotNull(s)` and `checkNotNull(s)` can be dropped from your code.
|
|
|
|
|
|
==== Noncompliant code example
|
|
|
|
[source, kotlin,diff-id=1,diff-type=noncompliant]
|
|
----
|
|
val s: String = ""
|
|
if (s != null) { doSomething() } // This statement is always true
|
|
----
|
|
|
|
==== Compliant solution
|
|
|
|
[source, kotlin,diff-id=1,diff-type=compliant]
|
|
----
|
|
val s: String = ""
|
|
doSomething()
|
|
----
|
|
|
|
==== Noncompliant code example
|
|
|
|
[source, kotlin,diff-id=2,diff-type=noncompliant]
|
|
----
|
|
val s: String = ""
|
|
if (s == null) { doSomething() } // This statement is always false.
|
|
----
|
|
|
|
==== Compliant solution
|
|
|
|
[source, kotlin,diff-id=2,diff-type=compliant]
|
|
----
|
|
val s: String = ""
|
|
----
|
|
|
|
==== Noncompliant code example
|
|
|
|
[source, kotlin,diff-id=3,diff-type=noncompliant]
|
|
----
|
|
val s: String = "ABC"
|
|
return s ?: "" // This ?: is useless.
|
|
----
|
|
|
|
==== Compliant solution
|
|
|
|
[source, kotlin,diff-id=3,diff-type=compliant]
|
|
----
|
|
val s: String = "ABC"
|
|
return s
|
|
----
|
|
|
|
==== Noncompliant code example
|
|
|
|
[source, kotlin,diff-id=4,diff-type=noncompliant]
|
|
----
|
|
val s: String = ""
|
|
s!!.doSomething() //You do not need to assert that S is non-null.
|
|
----
|
|
|
|
==== Compliant solution
|
|
|
|
[source, kotlin,diff-id=4,diff-type=compliant]
|
|
----
|
|
val s: String = ""
|
|
s.doSomething
|
|
----
|
|
|
|
|
|
== Resources
|
|
|
|
=== Documentation
|
|
|
|
* https://kotlinlang.org/docs/null-safety.html#nullable-types-and-non-null-types[Kotlin Documentation - Null Safety]
|
|
* https://kotlinlang.org/docs/strings.html[Kotlin Documentation - Strings]
|
|
|
|
=== Articles & blog posts
|
|
|
|
* https://blog.logrocket.com/complete-guide-null-safety-kotlin/[A complete guide to null safety in Kotlin]
|