Is there a built-in interface that I can use to accept everything that has a toString() method?
In other words, how to change the signature of acceptsStringables()
to make it work?
fun acceptsStringables(text: String) {
println(text.toString())
}
class Foo {
override fun toString(): String { return "hello world" }
}
fun main() {
acceptsStringables(Foo())
}
broot
October 8, 2021, 3:38pm
2
Yes, it’s… Any
. In Java/Kotlin all objects have the toString()
method. In Java primitives don’t have it, but Kotlin tries to unify primitives and objects, so even integers, etc. have it.
3 Likes
al3c
October 8, 2021, 3:53pm
3
Just take the string then. It’s clear you’re not doing anything else with this object.
(In case you might need the string, then you could take a lambda returning the string)
That is correct, but I want users of my function to be able to call it like acceptsStringables(foo)
instead of acceptsStringables(foo.toString())
.
fun acceptsStringables(obj: Any) {
println(obj.toString())
}
class Foo {
override fun toString(): String { return "hello world" }
}
fun main() {
acceptsStringables(Foo())
}