2011-07-28 60 views
1

我正尝试在地图上创建订阅者。scala.collection.script.Message上的scala模式匹配

这里是代码:

type Msg = Message[(SomeObject)] with undoable 
class mySub extends Subscriber[Msg,HashMap] { 
    def notify(pub:HashMap, evt: Msg) = { 
     evt match{ 
      case Include(NoLo,x) => println(x) 
     } 
    } 

} 
在上面的通知,如果我只是打印EVT我得到的输出

: - 包括(NOLO,someobject)......但如果我尝试的情况下包含的代码不会编译说法找到:包含要求:信息

包含不是消息的子类吗?你怎么测试等包括,删除等不同的消息..

回答

1

我能得到这个编译:

import collection.mutable._ 
import collection.script._ 
type K = Int 
type V = Int 
type Msg = Message[(K, V)] with Undoable 
class mySub extends Subscriber[Msg, HashMap[K, V]] { 
    def notify(pub: HashMap[K, V], evt: Msg) = { 
    (evt: Message[(K, V)]) match { 
     case Include(NoLo, x) => println(x) 
    } 
    } 
} 

搞笑的是,当Undoable混合的模式匹配将无法编译...

+0

我能够使用EVT匹配{case x:Include [(K,V)] => println(x.elem._1) – scala

0

多一点冗长,但这里是我想出了:

import scala.collection.mutable.{HashMap, Subscriber, Publisher, Undoable, ObservableMap} 
import scala.collection.script.{Message, Update, Include, Reset, Remove, Script} 

class MySub extends Subscriber[Message[(Int,Int)] with Undoable, ObservableMap[Int, Int]] { 
def notify(pub: ObservableMap[Int, Int], evt: Message[(Int, Int)] with Undoable) = evt match { 
    case update: Update[(Int, Int)] => println("Update: " + update) 
    case include: Include[(Int, Int)] => println("Include: " + include) 
    case reset: Reset[(Int, Int)] => println("Reset:" + reset) 
    case remove: Remove[(Int, Int)] => println("Remove: " + remove) 
    case script: Script[(Int, Int)] => println("Sript: " + script) 
} 
} 

当你注意,您必须引用的信息的子类的ELEM VAL拿到钥匙或 价值。

+1

问题是,你不应该匹配'case x :X [A]'作为关于'A'参数化的信息由于擦除而丢失。在这种情况下,它是安全的,但它不是一般情况。 –