Search code examples
scalapostfix-operator

Scala infix / postfix operators


I want to make the following code work, but I get an compile error: ' object A#c does not take parameters'

"b" c d

If I leave off 'd' the code compiles just fine. It must have something to do with infix/postfix operators which are new for me. Could somebody please help me make the above code work, and also explain to me (or give me some pointers) why the above code syntax is not working?

My class definitions:

object A {
    implicit def stringToA(b: String) : A = new A(b)
}

class A(private val b: String) {

    object c {
        println("c")

        def d: Unit = {
            println("d!")
        }
    }
}

Solution

  • in scala a op b is a.op(b), so your "b" c d will be "b".c(d), but what you want is "b".c.d, so you will need to write it fully.

    If you really need to write it "b" c d, you could try to make d an arg of a method c, for instance

    trait D {}
    
    object d extends D
    
    class A {
    
       def c(ignored: D) = println("d!")
    
    }
    

    or possibly

    class A {
    
       object c {
          def apply(ignored: D) = println("d!")
       }
    }