模糊重载:修复它还是尝试别的东西?

时间:2016-01-06 15:52:03

标签: scala implicit scala.js scala.rx scalatags

背景:我正致力于将scala.js / scalatagsscala.rx一起使用。我想要实现的是使用运算符样式将html输入中的值绑定到Rx Var。这就是我要做的事情:

implicit class BoundHtmlInput(input: Input) {
  def bindTextTo(v: Var[String]): Input = {
    input.oninput = { (e: dom.Event) => v() = input.value}
    input
  }

  def bindNumberTo(v: Var[Int]): Input = {
    input.oninput = {(e: dom.Event) => v() = input.valueAsNumber}
    input
  }

  def ~>[T](v: Var[T])(implicit ev: T =:= Int): Input =
     bindNumberTo(v.asInstanceOf[Var[Int]])

  def ~>[T](v: Var[T])(implicit ev: T =:= String): Input = 
     bindTextTo(v.asInstanceOf[Var[String]])
}

它适用于方法调用,但对于运算符~>调用失败。错误如下:

Error:(43, 70) ambiguous reference to overloaded definition,
both method ~> in class BoundHtmlInput of type [T](v: rx.Var[T])(implicit ev: =:=[T,String])org.scalajs.dom.html.Input
and  method ~> in class BoundHtmlInput of type [T](v: rx.Var[T])(implicit ev: =:=[T,Int])org.scalajs.dom.html.Input
match argument types (rx.core.Var[String])

我对asInstanceOf的使用情况也不满意。

我希望这能提供足够的背景。我的问题是,实现我想要的更好的方法是什么?

1 个答案:

答案 0 :(得分:2)

直接使用Var[Int]Var[String],带有虚假含义以抵御双重删除后的删除:

def ~>[T](v: Var[Int]): Input =
  bindNumberTo(v)

def ~>[T](v: Var[String])(implicit dummy: DummyImplicit): Input = 
  bindTextTo(v)

如果您有更多类型需要处理,可以根据需要添加尽可能多的DummyImplicit

def ~>[T](v: Var[Boolean])(implicit dummy1: DummyImplicit,
    dummy2: DummyImplicit): Input = 
  bindBooleanTo(v)