Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calling multiple functions with same instance in scala

Tags:

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
like image 563
scout Avatar asked Dec 12 '22 22:12

scout


2 Answers

How about this:

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

Or:

scala> { import c._
     |   examineColor
     |   bargain(300)
     |   buy
     | }
like image 116
Eastsun Avatar answered Feb 13 '23 02:02

Eastsun


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
like image 36
Randall Schulz Avatar answered Feb 13 '23 03:02

Randall Schulz