質問

I have a Scala program below:

object Fun extends App {
  class kid {
    def on = new kid
    def the(block: => Unit) = { block; "Scala is awesome!" }
  }

  println((new kid on) the {})
}

That println((new kid on) the {}) line prints:

Scala is awesome!

How can I make usage of this line even more English like in Scala?

EDIT: Another approach by @Erik Allik :

object Fun extends App {
  class kid {
    def onThe(block: => Unit) = { block; "Scala is awesome!" }
  }
  println(new kid onThe {})
}
役に立ちましたか?

解決

I think you can't make this work without the parens; without them the postfix call will cause ambiguity. I would just accept the fact that most of the time you can't achieve full English like sentence structure in most non-trivial cases and use a workaround such as onThe or skipping the the part and making on infix.

'the' is unneeded anyway because it's statically deduceable from context whether you mean a pre-existing name (the) or a new name i.e. free variable (a).

Also, I don't even find it very important or useful to achive 100% English like sentences unless it's a competition. In practice it might actually make things less readable and much more convoluted under the hood. If you really need something like natural language like DSL, define a new language grammar using Scala's powerful parser combinators. You should even be able to write, say, an Eclipse plugin to syntax highlight your custom DSL.

他のヒント

This might improve readability a bit. A common idiom would be to use a companion object to get rid of the new. If you can live with the added . you can get rid of some additional parentheses.

object Fun extends App {

  class Kid() {
    def the(block: => Unit) = { block; "Scala is awesome!" }
  } 

  object Kid {
    def on = new Kid()
  }

}

Then you can call your function in that way:

scala> println ( Kid.on the {} )
Scala is awesome!
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top