Scala中的DSL是什么? [英] What is DSL in Scala?

查看:290
本文介绍了Scala中的DSL是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过各种与Scala相关的材料,DSL术语在很多地方都被使用。

Going through various Scala related material, term DSL is used at many places.

Google搜索表明它是域特定语言。

Google search tells it is Domain specific language.

到底是什么意思,为什么在学习其他语言(如Java)时没有遇到这个术语?

What exactly it means, and why is it that this term doesn't comes across while learning other languages like Java?

推荐答案

正如其他人指出的那样,问题的第一部分(什么是DSL?)基本上由

As others have pointed out, the first part of the question ("what is a DSL?") is essentially answered by What is a DSL and where should I use it?

I会尝试回答第二部分:为什么DSL在Scala中如此受欢迎?

I'll try to answer instead to the second part: why are DSLs so popular in Scala?

原因是Scala(与Java等其他语言相对)提供了很多

The reason is that Scala (as opposed to other languages like Java) offers many syntactic facilities to provide DSLs.

例如,Scala具有中缀方法应用程序:

For example, Scala has infix method applications:

someObject.someMethod(someArgument)

// can be written as

someObject someMethod someArgument

这使得在语言中引入自定义操作符变得非常容易。一个著名的例子是 akka DSL,用于向演员发送消息:

This makes introducing custom "operators" very easy in the language. A notable example is the akka DSL for sending messages to an actor:

actor ! message

这是一种模拟Erlang语法的DSL。

which is a DSL mimicking the syntax of Erlang.

Scala中语法工具的另一个示例是跟踪块参数(不确定其名称是否准确):

Another example of a syntactic facility in Scala is the "trailing block argument" (not sure it has a precise name):

def someMethod(x: Int)(y: String) = ???

// can be invoked as
someMethod(42)("foo")

// but also as
someMethod(42) { "foo" }

当最后一个参数为函数时,这非常有趣:

which is very interesting when the last parameter is a function:

def someOtherMethod[A, B](x: A)(f: A => B): B = ???

someOtherMethod(42) { a =>
  // ...a very long body
}

其他语言,通常将块( {...} )保留给内置的控制流结构(例如 if while for 等),但是在Scala中,您可以使用此语法工具来构建类似于已构建的自定义方法-控制结构中。

In other languages, blocks ({ ... }) are usually reserved to built-in control-flow structures (such as if, while, for, etc), but in Scala you can use this syntactic facility to build custom methods that resemble built-in control structures.

仅这两个功能就足以说明DSL为什么在Scala社区如此普遍。

Those two features alone are distinctive enough for explaining why DSL are so pervasive in the Scala community.

深入探讨,我们还可以提及隐式转换,该转换允许向任何现有类型添加自定义方法。例如

Digging a bit deeper, we can also mention implicit conversions, which allow to add custom methods to any existing type. For example

implicit class TimesOps(x: Int) {
  def times(y: Int): Int = x * y
}

// then use as

2 times 4 // 8

此示例结合了infix方法应用程序的使用和隐式转换。

This example combines the use of infix method application and implicit conversions.

这篇关于Scala中的DSL是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆