I'm confused about operator overloading. say I've ...
# getting-started
y
I'm confused about operator overloading. say I've got a
class Foo
and I'd like to override
Foo + String
and
String + Foo
, such that both return a
Foo
. the first part is easy enough, just implement
operator fun plus(s: String): Foo
inside the definition of
class Foo
. for the second part, attempting to add an extension function
operator fun String.plus(foo: Foo): Foo
makes kotlin complain that I'm shadowing
operator fun plus(other: Any?): String
is there a way around this (and should I even go that way)?
v
It does not tell that you are shadowing that function, it tells you that function is shadowing your extension method as member functions always have precedence over extensions functions, so your extension function would never be used, so no.
thank you color 1
r
Just to add some context on why this would be a bad idea even if it were possible: it's a very common pattern (especially in Java so you may see it in converted code) to do something like
Copy code
log("error in foo: " + myFoo);
with the expectation this would call myFoo.toString and add to the log message. If what you propose were possible, it'd instead construct a new Foo and then call toString on that, which would be a completely unexpected and confusing log message. There's probably even more serious things it would also break but this alone would be reason to avoid it.
d
As an alternative, you could consider creating an infix function instead of operator overloading. This would allow similar reading of the code, but avoid operators
y
thanks everyone.
👌 1