模棱两可的重载:修复它还是尝试其他方法?
Ambiguous overloading: fix it or try something else?
背景:我正在研究如何使用 scala.js/scalatags together with scala.rx。我想要实现的是使用运算符样式将 html 输入的值绑定到 Rx Var
s。这是我的工作:
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
的使用也不满意。
我希望这提供了足够的上下文。我的问题是,实现我想要的目标的更好方法是什么?
直接使用Var[Int]
和Var[String]
,用虚拟隐含来对抗double-def-after-erasure:
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)
背景:我正在研究如何使用 scala.js/scalatags together with scala.rx。我想要实现的是使用运算符样式将 html 输入的值绑定到 Rx Var
s。这是我的工作:
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
的使用也不满意。
我希望这提供了足够的上下文。我的问题是,实现我想要的目标的更好方法是什么?
直接使用Var[Int]
和Var[String]
,用虚拟隐含来对抗double-def-after-erasure:
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)