Home > Blockchain >  Kotlin - Is it possible to check for operator precedence
Kotlin - Is it possible to check for operator precedence

Time:11-19

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:

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.

CodePudding user response:

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.

  • Related