帮助Scala中的泛型函数

时间:2011-08-03 18:50:45

标签: generics scala

我有以下代码,但它没有编译。我认为问题是我需要告诉它T必须是Event的子类吗?

scala.swing.Reactions.Reaction的类型是PartialFunction [Event,Unit]

错误是: 类型不匹配; found:需要PartialFunction [T,Unit]:scala.swing.Reactions.Reaction

import scala.swing.event.MousePressed
import scala.swing.Component
import scala.swing.Reactions

import reactive.EventSource
import reactive.EventStream

class TypeIssue {
  type PartialAdapter[T] = (T => Unit) => PartialFunction[T, Unit]

  def adMousePressed(c: Component)(f: MousePressed => Unit): PartialFunction[MousePressed, Unit] = {
    case MousePressed(`c`, point, mods, clicks, triggersPopup) => f
  }

  def eventToStream[T](r: Reactions, ad: PartialAdapter[T]): EventStream[T] = {
    val v = new EventSource[T] {}
    r += ad(e => v.fire(e)) // error on this line
    v
  }
}

1 个答案:

答案 0 :(得分:2)

ad返回PartialFunction [MousePressed,Unit]。 Reactoins + =期望一个反应是PartialFunction [事件,单位]。 PartialFunction在其第一个类型参数中是逆变的,因此PartialFunction [MousePressed,Unit]不被视为PartialFunction [Event,Unit]

只需将adreturn类型设为反应即可。这是代码(没有反应类型)

import scala.swing.event.MousePressed
import scala.swing.Component
import scala.swing.Reactions


class TypeIssue {
  type PartialAdapter[T] = (T => Unit) => Reactions.Reaction

  def ad(c: Component)(f: MousePressed => Unit): Reactions.Reaction = {
    case MousePressed(`c`, point, mods, clicks, triggersPopup) => f
  }

  def eventToStream[T](r: Reactions, ad: PartialAdapter[T]): Unit = {

    r += ad(e => ()) // error on this line
    ()
  }
}
相关问题