开发者

Help with generic function in Scala

I have the following code but it doesn't compile. I think the problem is that I need to tell it that T has to be a subclass of Event?

The type of scala.swing.Reactions.Reaction is PartialFunction[Event, Unit]

The error is: type mismatch; found : PartialFunction[T,Unit] required: 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: M开发者_如何学PythonousePressed => 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
  }
}


ad returns a PartialFunction[MousePressed, Unit]. Reactoins+= expects a Reaction which is PartialFunction[Event, Unit]. PartialFunction is contravariant in its first type argument, so PartialFunction[MousePressed, Unit] is not considered as a PartialFunction[Event, Unit]

Just make adreturn type a Reaction. Here is the code (without the reactive types)

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
    ()
  }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜