代码之家  ›  专栏  ›  技术社区  ›  jhegedus

是否需要导入伴随对象中的隐式转换方法?与“Scala for the急躁”一书的矛盾

  •  4
  • jhegedus  · 技术社区  · 11 年前

    下面的代码不起作用,但根据“Scala for The急躁”一书(请参阅下面的摘录),它应该起作用。那么我在这里不明白什么?在最近的Scala版本中,隐式转换的规则是否发生了变化(2.8对2.10)?

    编辑:

    看了这个之后 question 我意识到 b.hello 需要更改为 (b:A).hello 。这不是很含蓄。有什么办法可以解决这个问题吗?

    编辑2:

    阅读更多内容后 this 除了进口,似乎没有别的办法了。

    object A {
      implicit def b2a(b:B)=new A
    }
    class A{
      def hello=println("hello")
    }
    class B 
    
    object ImplicitConversion extends App{
      val b=new B
      b.hello
    }
    

    enter image description here

    2 回复  |  直到 8 年前
        1
  •  3
  •   Ionuț G. Stan    11 年前

    这是因为Scala编译器无法确定您想要转换 B A 只要看看这段代码:

    val b = new B
    b.hello // I know the source type is B, but what's the target type?
    

    考虑以下情况: C 类似于您的 A. 。Scala应该选择两种转换中的哪一种?要求Scala搜索系统中的所有其他伴随对象,以便从已知的源类型进行可能的隐式转换,这太过分了。很有可能最终会得到一个模棱两可的结果。

    在您的情况下,最简单的解决方案是移动 B A. 从的伴随对象转换 A. 到的伴随对象 B .

    class A {
      def hello=println("hello")
    }
    
    class B 
    
    object B {
      implicit def b2a(b:B)=new A
    }
    
    object ImplicitConversion extends App {
      val b=new B
      b.hello
    }
    
        2
  •  0
  •   jhegedus    11 年前

    Stan提出的解决方案令人满意,因为:

    object B  {
      implicit def b2a(b:B)=new A 
    }
    
    class A{
      def hello=println("hello")
    }
    
    class B 
    
    class C extends B
    
    
    object ImplicitConversion extends App{
    
      val c=new C
      c.hello
    
    }
    

    这里我只需要包含隐式转换 b2a 在里面 B 的伴随对象。

    然后我可以使用 B A .

    推荐文章