tags:

views:

107

answers:

2

is there any way I can achieve the following in scala

with new Car() {
     examineColor
     bargain(300)
     buy
}

instead of

val c = new Car()
c.examineColor
c.bargain(300)
c.buy
+10  A: 

How about this:

scala> val c = new Car {
     |     examineColor
     |     bargain(300)
     |     buy
     | }

Or:

scala> { import c._
     |   examineColor
     |   bargain(300)
     |   buy
     | }
Eastsun
+1 for the second option. The first will create a subclass of `Car` and execute the methods in its constructor, which may not be what is expected.
Ben Lings
+2  A: 

Assuming those methods (examineColor, bargain and buy) are invoked for their side-effects and not for their return values, you can use the chaining pattern in which each of those methods returns this, allowing you to write code like this:

val c1 = new Car()
c1.examineColor.bargain(300).buy
Randall Schulz