Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/google-sheets/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Scala:对于不明确的隐式转换,选择哪一种?_Scala_Implicit Conversion_Implicit - Fatal编程技术网

Scala:对于不明确的隐式转换,选择哪一种?

Scala:对于不明确的隐式转换,选择哪一种?,scala,implicit-conversion,implicit,Scala,Implicit Conversion,Implicit,为什么下面的(toy)示例在Scala中编译时没有任何问题,以及用于决定选择哪个隐式转换的规则是什么 object test1 { class MyInt(val v: Int) { def +(other: MyInt) = new MyInt(v + other.v) override def toString = v.toString } class MyIntMod10(vparam: Int) { val v = vparam % 10; d

为什么下面的(toy)示例在Scala中编译时没有任何问题,以及用于决定选择哪个隐式转换的规则是什么

object test1 {
  class MyInt(val v: Int) {
    def +(other: MyInt) = new MyInt(v + other.v)
    override def toString = v.toString
  }
  class MyIntMod10(vparam: Int) {
    val v = vparam % 10;
    def +(other: MyIntMod10) = new MyIntMod10(v + other.v)
    override def toString = v.toString
  }

  val a = new MyInt(7);                           //> a  : test1.MyInt = 7
  val b = new MyIntMod10(7);                      //> b  : test1.MyIntMod10 = 7
  implicit def toIntMod10(x: MyInt) = new MyIntMod10(x.v)
                                                  //> toIntMod10: (a: test1.MyInt)test1.MyIntMod10
  val c1 = a + b                                  //> c1  : test1.MyIntMod10 = 4
  val c2 = b + a                                  //> c2  : test1.MyIntMod10 = 4

  implicit def toInt(x: MyIntMod10) = new MyInt(x.v) //> toInt: (b: test1.MyIntMod10)test1.MyInt
  val c3 = a + b                                  //> c3  : test1.MyInt = 14
  val c4 = b + a                                  //> c4  : test1.MyIntMod10 = 4
}
我希望最后两行会因为歧义而产生编译时错误,但事实并非如此。(据我所知,c1和c3的值不同,这直接说明了计算c3时的模糊性!如果我错了,请纠正我。)


我知道在Scala的当前版本中,编译器会解决一些不明确的隐式调用,但我看不出给定的示例代码是如何属于这些特殊情况的

对于行设置
c1
c3
,调用的
+
方法是在
MyInt
上定义的方法。在这些情况下,编译器首先尝试将
+
方法(
b
)的参数转换为
MyInt
。同样,对于
c2
c4
,调用的
+
方法是在
MyIntMod10
上定义的方法,因此编译器希望将
a
转换为
MyIntMod10

这适用于
c2
c3
c4
,其中有适当的隐式表达式


对于
c1
的情况,没有隐式(此时)将
b
转换为
MyInt
,因此,它然后寻找一种方法将
a
转换为某种具有
+
方法的东西,该方法可以将
MyIntMod10
作为一个参数,从而找到对
MyIntMod10
的隐式转换以应用于
a
,并将其转换为
MyIntMod10
,正如您所观察到的那样。

谢谢。这是有道理的。你能给我指一下明确说明这些行为的规范吗。