2012-07-08 31 views
0

可以在Scala中定義泛型運算符嗎?Scala中的通用運算符

斯卡拉讓我映射任意運算符的函數,這是非常有用的。但是,如果我希望操作員在給定應用程序狀態的情況下進行更改,這似乎是一種限制。


舉一個例子:我有一個包含用戶和表的關係表。每個關係都有一個類型,例如:「與朋友一起」,「與......合作」等。 基於我的域模型,我希望DSL允許:is(john friends-with mary)。在這種情況下,johnmary都將是對象User,其將具有通用運算符def <relationship> (a:User): Boolean = {...}


我想達到的就是Dynamic允許我做的事情(見答案)。描述適合:

啓用動態調用的標記特徵。此特徵的實例x允許爲任意方法名稱meth和參數列表args調用x.meth(args)。如果一個調用不是由本機支持的,它會被重寫爲x.applyDynamic(「meth」,args)。

點擊此處瞭解詳情:http://www.scala-lang.org/api/current/scala/Dynamic.html

+0

你能澄清一點你是什麼意思與<關係>?在實現/覆蓋它時可以更改此方法的符號? – sschaef 2012-07-08 23:29:49

+1

您是否知道typeclasses? http://marakana.com/s/scala_typeclasses,1117/index.html谷歌搜索'斯卡拉typeclasses'讓你更深入挖掘。假設你想爲其他類型的''方法,而不是用戶。 – pedrofurla 2012-07-08 23:34:07

+0

你期望表達'約翰朋友和瑪麗'來回報什麼? – 2012-07-09 00:02:46

回答

4

看質量的動態,這將可在斯卡拉2.10(這是實驗上的Scala 2.9)。

例如:

scala> :paste 
// Entering paste mode (ctrl-D to finish) 

case class User(name: String) extends Dynamic { 
    def applyDynamic(relationship: String)(to: User) = 
    Relation(relationship, this, to) 
} 
case class Relation(kind: String, from: User, to: User) 

// Exiting paste mode, now interpreting. 

defined class User 
defined class Relation 

scala> User("john") friendsWith User("mary") 
res0: Relation = Relation(friendsWith,User(john),User(mary)) 
+0

不錯的代碼。但我仍然不確定問題的作者是用「通用」來表示的。 – pedrofurla 2012-07-09 01:28:37

+0

他不希望在一組固定的方法中使用硬編碼的關係類型,而是使用稱爲參數的方法的名稱作爲底層結構的方式(在這種情況下爲applyDynamic) – 2012-07-09 20:09:10