我想写一个允许如下语法的系统:
a b/c
A是一个类,B是一个特定的项(不是任意的字符串),C是一个int。
我知道你能做到
a b c
成为
a.b(c)
然而,第一种语法将更优雅,任何解决方案都将帮助我扩展我的scala知识:)
如果这些对你来说足够好…
a { b/c } a ( b/c )
…这将起到关键作用:
trait Term { def / (n:Int):(Term,Int) = (this,n) } case object Inc extends Term // any other terms declared likewise
然后你的班级可以这样支持它:
class A { def apply(t:(Term,Int)) = t match { case (Inc,n) => n + 1 // further term implementations } }
用途:
scala> val a = new A a: A = A@1c2628 scala> a { Inc / 8 } res28: Int = 9 scala> a ( Inc / 8 ) res29: Int = 9