Question

I want to define one (or two, depends on how you look at it) operators in scala.

Something like this : _ ==> _ | _ where the underscore stands for the arguments. The tricky part is, that the operator should be used in an constructor to set the fields of the object.

I wrote a small example, using implicits and a wrapper object. But that approach clearly does not work. I don't know, how i can set the fields of the current object.

In this example, every create object from type B should have set its fields to "B", 44 and "foo". The result of "B" ==> 44 | "foo" should be the same as this.a = "B"; this.b = 44; this.c = foo. Is there a way to achieve that?

Thanks!

abstract class Top {

  var a = "a"
  var b = 3
  var c = "c"
  implicit def js2WJ(js: String) : Wrapper = {
    new Wrapper(js)
  }

}

case class B() extends Top
{
    "B" ==> 44 | "foo"
}

class Wrapper(js: String)
{
    var ju : Option[Int] = None 
    var cs : Option[String] = None
    def ==>(j: Int): Wrapper = {
      ju = Some(j)
      this
    }
    def | (cs: String) =
    {
      this.cs = Some(cs) 
    }
}
Was it helpful?

Solution

Is this what you needed?

abstract class Top {
  var a = "a"
  var b = 3
  var c = "c"
  implicit def js2WJ(js: String): TopBuilder = TopBuilder(js, b, c, this)
}

case class TopBuilder(a: String, b: Int, c: String, top: Top) {
    def ==> (j: Int) = copy(b = j)
    def | (s: String) = copy(c = s) toTop
    def toTop {
        top.a = a
        top.b = b
        top.c = c
    }
}


object B extends Top {
    "B" ==> 44 | "foo"
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top