Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Kotlin – Is it possible to check for operator precedence

Let’s say I have the following class:

data class Foo(var name: String) {
    operator fun plus(foo: Foo): Foo {
        name += foo.name
        return this
    }
}

Which is then used like this:

val foo1 = Foo("1")
val foo2 = Foo("2")
val foo3 = Foo("3")

foo1+foo2+foo3
println(foo1.name) // 123

Now, what if I wanted different behavior depending on whether the operations are chained like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

foo1+foo2+foo3

Or like this:

(foo1+foo2)+foo3

In both cases foo1’s name would be 123, but let’s say that in the second case I would want foo1’s name to be (12)3.

Is there a way to add a condition to the plus function, which checks whether the foo that it is called on originates from within parentheses/has a higher precedence or not.

>Solution :

No, that is not possible, because that makes no sense tbh. The compiler will just resolve the order of operations, brackets just indicate that 1+2 should resolve first and the result should be added to 3. There is no concept of brackets anymore in that result, you just have the outcome.

What is confusing you is that you are abusing the plus function to do something people wouldn’t expect. You should not use the plus function to mutate the object it is called upon, this is not expected behaviour. Users will expect the plus function to return a new object not a mutation of the left or right operand.

In your case:

operator fun plus(foo: Foo): Foo {
    return Foo(name += foo.name)
}

Don’t do something different lest you want other people to be really confused. Fyi plusAssign is a mutating function, but still wouldn’t allow you to do what you want. To achieve that you’d probably need to write your own parser and parse the operands and operators yourself.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading