【发布时间】:2021-04-29 13:14:52
【问题描述】:
我正在尝试使用以下语法制作 scala dsl:
val a = Agent() setup { agent => // agent reference.
agent add "Hello World!"
}
a add "Not allowed" // Atm this is allowed.
我可以在 setup 函数体之外调用方法 add 并调用 add 方法我必须在 setup 函数体的开头写 agent =>。
我所做的atm是一个特质代理:
trait Agent {
def setup(f: Agent => Unit): Agent
def add(s: String): Agent
}
case class AgentImpl(strings: Seq[String]) extends Agent {
override def setup(f: Agent => Unit): Agent = {
f(this)
this
}
override def add(s: String): Agent = copy(strings = strings:+s)
}
object Agent {
def apply(): Agent = AgentImpl(Seq.empty)
}
我要做的是:
val a = Agent() setup { // No more references to agent
add "Hello World!"
}
a add "Not allowed" // This mustn't be allowed. Compilation error.
我没有在设置函数主体的开头使用agent => 引用代理,如果我尝试在设置函数主体之外进行添加,则会出现错误。
这在 Scala 中可行吗?
我可以更改代码的每一部分,添加任意数量的特征/类/对象和其他内容,但不能更改我的 DSL 的语法。
【问题讨论】:
标签: scala functional-programming higher-order-functions