我正在尝试使用Scala编写DSL。我最初希望能够写出类似的东西
defType "foo"
使用时
我以为以下应该有效:
的src /主/秤/ Test.scala
class Dsl {
def defType(name: String) = "dummy"
}
object Dsl {
def apply() = new Dsl()
}
class UseDsl {
def foo() = {
val dsl = Dsl()
import dsl._
dsl defType "foo"
defType("foo")
defType "foo"
}
}
这无法编译:
[error] Test.scala:15:17: ';' expected but string literal found.
[error] defType "foo"
[error] ^
[error] one error found
[error] (Compile / compileIncremental) Compilation failed
显式地给dsl
使用空格来分隔方法名称和参数。
隐式使用dsl
和括号来表示参数与方法名称有效。
试图同时使用它们都失败了。
有没有办法让它工作?
一旦这个工作,我计划扩展DSL以支持这样的事情
defType "foo"
-- "bar1" :: "quz"
-- "bar2" :: "quz"
这相当于
dsl.defType("foo").
--(ImplicitClass("bar1", dsl).::("quz")).
--(ImplicitClass("bar2", dsl).::("quz"))
这是我能够上班的东西吗?我认为ImplicitClass
可以使用类似的声明
def implicit ImplicitClass(a: String, implicit dsl: Dsl) = ...
但很明显,我对如何让Scala在代码中添加内容的理解并不完美。
如果它不起作用,有哪些最小的增加可以让它工作?
build.sbt
ThisBuild / organization := "test"
ThisBuild / version := "0.0.1-SNAPSHOT"
ThisBuild / scalaVersion := "2.12.8"
//
// Projects
//
lazy val root = (project in file("."))
不,method argument
无效。对于没有括号的中缀方法调用,您必须这样做
val1 method1 val2 method2 val3 ...
这个链可以在没有参数的方法中结束,也可以在最后一个方法的参数中结束,第一个不太安全。
即使是当前类型的成员,你需要做this method1 ...
,不能像this
那样省略this.method1(...)
。