scout
scout

Reputation: 2386

calling multiple functions with same instance in scala

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

Upvotes: 5

Views: 1246

Answers (2)

Randall Schulz
Randall Schulz

Reputation: 26486

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

Upvotes: 3

Eastsun
Eastsun

Reputation: 18859

How about this:

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

Or:

scala> { import c._
     |   examineColor
     |   bargain(300)
     |   buy
     | }

Upvotes: 10

Related Questions