KT.NULLABLE_TO_STRING_CALL

Method 'toString' with a nullable receiver that may return the string 'null'

Turn on this rule to flag 'toString' calls with a nullable receiver that may return the string 'null'.

Noncompliant Code

Copy
fun foo(a: Any?): String {
    return a.toString()
}

fun bar(a: Any?): String {
    return "$a"
}

Compliant Code

Copy
fun foo(a: Any?): String {
    return a?.toString() ?: "-"
}

fun bar(a: Any?): String {
    return "${a ?: "-"}"
}

The content on this page is adapted from the Detekt Docs. Copyright ©2022 The Detekt Team. All rights reserved. https://detekt.dev/comments.html