0

I need a configuration language with a little code. I'm trying to use scala. Can I write in Scala or in other JVM language something like

... = car() {
    title = "Experimental Car"
    engine = dieselEngine() {
        capacity = 1.9
    }
}

instead of

val c = car()
c.title = "Experimental Car"
c.engine = c.dieselEngine()
c.engine.capacity = 1.9

It is important, that dieselEngine is method on car.

2
  • what are those dots? why you need something like that? if you need configuration, won't be better just read it from file? Commented Jun 4, 2014 at 11:19
  • Very strange that this completely legitimate question is downvoted. Commented Jun 4, 2014 at 11:33

3 Answers 3

1

Scala case classes provide exactly what you need:

case class Car(title: String, engine: Engine)

// A marker trait and several implementations
sealed trait Engine
case class DieselEngine(capacity: Double) extends Engine
case class ElectricEngine(capacity: Int) extends Engine

val c = Car(
  title = "Experimental car",
  engine = DieselEngine(capacity = 1.9)
)

See here for more.

Sign up to request clarification or add additional context in comments.

Comments

1

Try Groovy method with:

... = new Car().with {
  title = "Experimental Car"
  engine = dieselEngine().with {
    capacity = 1.9
    return this
  }
  return this
}

Comments

0

This is also supported nicely by Builders in the Groovy language. You'd have syntax

car {
    title: "Experimental Car"
    engine: dieselEngine {
        capacity: 1.9
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.