Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Warning when using Object's default toString #380

Open
albertvaka opened this issue Jun 21, 2024 · 1 comment
Open

Warning when using Object's default toString #380

albertvaka opened this issue Jun 21, 2024 · 1 comment

Comments

@albertvaka
Copy link

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
Copy link

fvasco commented Jun 21, 2024

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants