Nullable To String

ID

kotlin.nullable_tostring

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

Kotlin

Tags

null-safety, string

Description

Reports calls to toString() where the receiver has a nullable type.

Kotlin’s extension function Any?.toString() deliberately accepts nullable receivers and returns the four-character string "null" when the value is null. This means the call never throws, but it silently produces misleading output that is almost always unintentional.

Rationale

val name: String? = fetchName()   // may be null

val label = name.toString()       // FLAW — label becomes "null" (string) when name is null
log.info("User: $label")          // logs 'User: null' literally

val safe = name?.toString() ?: ""  // OK — empty string when null
val opt  = name?.toString()        // OK — null when null, handled by null-safety

Remediation

Replace value.toString() on a nullable receiver with one of the following:

  • value?.toString() ?: "" — return an empty string when the value is null.

  • value?.toString() — propagate null explicitly if the call site handles it.

  • Add an explicit null check before calling toString().