【发布时间】:2015-11-20 20:12:42
【问题描述】:
我有一个表示表达式的类层次结构,其中一些包含其他类型的对象。我想设置一些从包装类型到表达式类型的隐式转换,以便更容易构造表达式。我尝试了 3 个地方来定义隐式转换(如各种在线资源所建议的那样):一个被导入的对象(这个工作)、源类型的伴随对象(这有条件地工作,对于非重载方法)和一个伴随对象目标类型(这不起作用)。代码如下:
import scala.language.implicitConversions
// 1.
// If conversions are defined this way, the program compiles.
// But many sources insist that compiler also looks in the source/target companions for conversions.
object Conversions {
implicit def varToExpr(v: Var): VarExpr = new VarExpr(v)
implicit def constToExpr(c: Const): ConstExpr = new ConstExpr(c)
}
import Conversions._
class Var(val name: String)
class Const(val value: String)
// 2.
// These conversions do not work for e1-e4 (see below), but e5-e10 compile.
object Var {
implicit def varToExpr(v: Var): VarExpr = new VarExpr(v)
}
object Const {
implicit def constToExpr(c: Const): ConstExpr = new ConstExpr(c)
}
trait Expr {
def +(right: Expr): PlusExpr = PlusExpr(this, right)
def :+(right: Expr): PlusExpr = PlusExpr(this, right)
// 3.
// These do not work at all.
implicit def varToExpr(v: Var): VarExpr = new VarExpr(v)
implicit def constToExpr(c: Const): ConstExpr = new ConstExpr(c)
}
case class ConstExpr(c: Const) extends Expr
case class VarExpr(v: Var) extends Expr
case class PlusExpr(left: Expr, right: Expr) extends Expr
class Test {
def main(args: Array[String]) {
val a = new Var("a")
val b = new Var("b")
val c = new Const("c")
// Want to be able to write things like that.
// The first 4 work only with the 1-st way of defining the implicit conversions.
// For the 2nd way they give
// Error:(__, __) type mismatch;
// found : Const (or Var, or VarExpr)
// required: String
val e1 = a + b
val e2 = c + c
val e3 = (a + b) + c
val e4 = a + VarExpr(b)
// This compiles with both 1st and 2nd ways.
val e5 = ConstExpr(c) + b
val e6 = VarExpr(a) + c
val e7 = a :+ b
val e8 = c :+ c
val e9 = (a :+ b) :+ c
val e10 = a :+ VarExpr(b)
}
}
我尝试定义两个运算符:+ 和 :+。对于+,转换似乎与String 的转换发生冲突,因此只有第一种方式(导入对象)真正有效。对于 :+ 源类型的伴随对象也可以。尽管某些消息来源(例如http://docs.scala-lang.org/tutorials/FAQ/finding-implicits.html)说了什么,但在目标类型的伴随对象中定义转换似乎不起作用。
问题是,定义此类转换的适当方法是什么。第一种方式似乎经常在标准库中使用(例如,JavaConversions/JavaConverters)。但是正确的方法是什么?
UPD 1
正如 Alexey Romanov 所指出的,我试图在 trait Expr 中定义转换,而不是在它的伴随对象中。拥有这些:
object Expr {
implicit def varToExpr(v: Var): VarExpr = new VarExpr(v)
implicit def constToExpr(c: Const): ConstExpr = new ConstExpr(c)
}
允许写类似的东西
val e12: Expr = a
但不是
val e11: Expr = a :+ VarExpr(b)
UPD 2
正如@cchantep 所暗示的,在伴随对象中定义转换的问题可能具有优先权。在Predef.scala我设法找到:
implicit final class any2stringadd[A](private val self: A) extends AnyVal {
def +(other: String): String = String.valueOf(self) + other
}
我从中了解到的是,如果 + 用于本身未定义 + 的类型的对象,编译器会尝试使用此定义。此外,+ 的这个定义显然会优先于伴随对象中定义的任何隐式转换。这可以解释我遇到的编译器错误。
【问题讨论】:
-
@cchantep 你能详细说明一下吗?您是否建议将
String转换为+运算符的优先级高于我在伴随对象中定义的转换?可能是这样,但到目前为止我还没有找到它的确切定义位置。 -
@cchantep 这也没有解释为什么不搜索目标类型
Expr的伴随对象,这是我在问题中链接的常见问题解答所建议的。 -
@AlexeyB。请参阅我关于
any2stringAdd的答案更新。
标签: scala