Kotlin / KEEP

Kotlin Evolution and Enhancement Process
Apache License 2.0
3.42k stars 362 forks source link

Warning when using Object's default toString #380

Open albertvaka opened 5 months ago

albertvaka commented 5 months ago

I haven't written a fully-fledged proposal yet, but I want to hear what the community thinks about this.

The default toString in Object is a footgun. The representation it prints is rarely what the user wants to see, but because it exists it makes the code compile with issues that can only be found at runtime.

In the following snippet, the developer forgot to use filePath.path and used just filePath instead. The Kotlin compiler will not catch this issue and the program will print something like FilePath@70177ecd which is definitely not the user intent.

class FilePath(val path : String)

fun main() {
    val filePath = FilePath("/tmp/myfile.txt")
    println(filePath)
}

println was used here for brevity, but this is more likely to happen when serializing arguments to text to be sent in JSON or a similar format.

My proposal is that the Kotlin compiler provides a warning when the toString method in Object is being called in your code.

fvasco commented 5 months ago

Your proposal isn't related to language evolution, please consider another channel: https://kotlinlang.org/community/