首页 文章

如何控制应用于方法参数的隐式转换的优先级?

提问于
浏览
1

假设代码:

class A
class B

class Something {
  def method(arg: A) = ???
  def method(arg: B) = ???
}

class C

object C {
  implicit def ctoa(c: C): A = ???
  implicit def ctob(c: C): B = ???
}

另外:

  • ABSomething 及其随播广告无法修改

  • 必须有从 CA 以及从 CB 的隐式转换,它们的优先级无关紧要

  • 除此之外,类 C 及其伴星可以自由修改

  • 当然,可以添加更多类型,含义等

现在,有没有办法进行编译:

(new Something).method(new C)

1 回答

  • 2

    我知道这不是你想要的,但我没有看到任何方法去做,除了将其中一个暗示到另一个范围 .

    class A
    class B
    
    class Something {
      def method(arg: A) = println("method(A)")
      def method(arg: B) = println("method(B)")
    }
    
    class C
    
    object C {
      implicit def ctoa(c: C): A = new A
    }
    
    object X {
      implicit def ctob(c: C): B = new B
    }
    

    然后你得到:

    scala> (new Something).method(new C)
    method(A)
    

    否则,您试图违反非歧义规则:"An implicit conversion is only inserted if there is no other possible conversion to insert."请参阅Programming in Scala .

相关问题