Martin Charlesworth
Martin Charlesworth

Reputation: 617

How can I get rid of the brackets in a scala DSL expression?

I'd like to be able to get rid of the brackets/parentheses in the following expression in my DSL:

substitute ("hello {0}" using "world")

The rest of the code looks like this:

class Rule(format: String) {
  def using(arggs: String*): Rule = { /* save the args */ return this }
  def execute() = { /* substitute params */ }
}

def substitute(rule: Rule) = rule.execute()
implicit def makeRule(format: String) = new Rule(format)

I've tried the apply() method but I don't think I can do it that way. Is there some scala magic out there I could use?

Upvotes: 4

Views: 392

Answers (2)

neutropolis
neutropolis

Reputation: 1894

Not an exact solution for your case (@RandallSchulz is absolutely right), but you may use a two-word approach:

class RuleHelper(val txt: String) {
  def using(arggs: String*): RuleHelper = { /* save the args */ return this }
  def execute() = { /* substitute params */ }
}

object substitute {
  def in(txt: String) = new RuleHelper(txt)
}

substitute in "hello {0}" using "world"

It's not as beautiful as you would like, but I think it reduces the accidental complexity.

Upvotes: 2

Randall Schulz
Randall Schulz

Reputation: 26486

Scala has it's own equivalent of the iamb / iambic meter (if you will) when you want to omit the . and the ( ... ):

target (skipped .) method (skipped () singleArgument (skipped ))

The singleArgument is optional.

Every dotless, parenless DSL-ish thing has to fit this pattern. It's why Scala internal DSLs are so often so stilted.

Upvotes: 3

Related Questions