Skip to content

Warning when using Object's default toString #380

Open
@albertvaka

Description

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.

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions