Scala隐式转换顺序

时间:2014-04-24 12:48:29

标签: scala

我有两个类似方法的对象〜(...)。我还定义了隐式转换,它应该将pair(String,A)转换为DemoObject或WopWopWop

class DemoObject[A](t: (String, A)) {
  def ~(t: (String, A)) = "demo"
}

class WopWopWop[A](t: (String, A)) {
  def ~(t: AnyVal) = "wop wop wop"
}

object ImplicitDemoConversions {
  implicit def pair2DemoObject[A](t: (String, A)) = new DemoObject(t)
}

object ImplicitWopWopWopConversions {
  implicit def pair2WopWopWop[A](t: (String, A)) = new WopWopWop(t)
}

然而,有点像

import ImplicitDemoConversions._
object Hello {
  def main(args: Array[String]): Unit = {
    import ImplicitWopWopWopConversions._
    val pair = ("LolTest" -> "A") ~ ("whoa" -> "wop wop wop")

    println(pair) 
  }
}

将打印回答演示,而不是预期 wop wop wop 。看起来scala编译器会忽略ImplicitWopWopWopConversions的第二次导入._

问题是为什么我认为(String,String)对应该转换为 WopWopWop ,我如何获得WopWopWop对象而不是DemoObject?

你可以在https://github.com/json4s/json4s/issues/121

找到真实的例子

1 个答案:

答案 0 :(得分:2)

您可以使用别名隐藏导入。

import ImplicitDemoConversions.{pair2DemoObject => i}
object Hello {
  def main(args: Array[String]): Unit = {
    import ImplicitWopWopWopConversions.{pair2WopWopWop => i}
    val pair = ("LolTest" -> "A") ~ ("whoa" -> "wop wop wop")

    println(pair) 
  }
}

修改

您的元组转换为DemoObject而不是WopWopWop的原因是因为DemoObject&n; ~方法参数类型比WopWopWop' S

就像这个例子一样:

object A {
    def m(x: AnyVal) { println(x) }
    def m(x: (Int, String)) { println(x) }

    // This will call the first method, because the second method can't be
    // applied to an Int
    a(1)
    // Either method could be applied to a (Int, String), but the second 
    // method will be chosen, because it's argument type is more specific.
    a((1 -> "hello"))
}