简体   繁体   中英

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" cd

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!")
        }
    }
}

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

If you really need to write it "b" cd , 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!")
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM