原文: Scala DSL tutorial - writing a web framework router, 作者: Tymon Tobolski 
译者按:
Scala非常适合实现DSL(Domain-specific language)。我在使用Scala的过程中印象深刻的是scalatest和spray-routing,
比如scalatest的测试代码的编写:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 
  | import collection.mutable.Stack import org.scalatest._ class ExampleSpec extends FlatSpec with Matchers {   "A Stack" should "pop values in last-in-first-out order" in {     val stack = new Stack[Int]     stack.push(1)     stack.push(2)     stack.pop() should be (2)     stack.pop() should be (1)   }   it should "throw NoSuchElementException if an empty stack is popped" in {     val emptyStack = new Stack[Int]     a [NoSuchElementException] should be thrownBy {       emptyStack.pop()     }    } } 
  | 
 
或者 akka-http的路由(route)的配置 (akka-http可以看作是spray 2.0的版本,因为作者现在在lightbend,也就是原先的typesafe公司开发akka-http):
1 2 3 4 5 6 7 8 9 10 11 12 
  | val route =   get {     pathSingleSlash {       complete(HttpEntity(ContentTypes.`text/html(UTF-8)`,"<html><body>Hello world!</body></html>"))     } ~       path("ping") {         complete("PONG!")       } ~       path("crash") {         sys.error("BOOM!")       }   } 
  | 
 
可以看到,使用Scala实现的DSL非常简洁,也符合人类便于阅读的方式。但是我们如何实现自己的DSL呢?文末有几篇参考文档,介绍了使用Scala实现DSL的技术,但是本文翻译的这篇文章,使用Scala实现了一个鸡蛋的web路由DSL,步骤详细,代码简单,所以我特意翻译了一下。以下内容(除了参考文档)是对原文的翻译。
      
      
        阅读全文