【问题标题】:Is "A with B" a type?“A with B”是一种类型吗?
【发布时间】:2014-01-05 14:27:14
【问题描述】:

在 Scala 中,我们像这样使用 mix-in:

class C extends A with B

我将这个声明理解为CA with B 的子类。这是真的?或者C 只是AB 的子类(我认为在不支持多继承的JVM 上是不可能的)?

如果A with B 是一个类型,为什么这条线不起作用?

classOf[A with B]

我认为A with B 类型的另一个原因是它可以用于模式匹配:

val c = new C
val u = c match { case a: A with B => 1 } // 1

【问题讨论】:

    标签: scala inheritance mixins


    【解决方案1】:

    我同意@Dylan。 A with B 只是一个类型定义。但是要让它与 classOf[T] 一起工作,它需要有一个由 Scala 生成的 Java classinterface

    scala> trait A
    defined trait A
    
    scala>   trait B
    defined trait B
    
    scala>   trait AB extends A with B
    defined trait AB
    
    scala>   class C extends A with B
    defined class C
    
    scala>   type TypeAB = A with B
    defined type alias TypeAB
    
    scala>   println(classOf[A])
    interface $line3.$read$$iw$$iw$A
    
    scala>   println(classOf[B])
    interface $line4.$read$$iw$$iw$B
    
    scala>   println(classOf[AB] )
    interface $line5.$read$$iw$$iw$AB
    
    scala>   println(classOf[C])
    class $line6.$read$$iw$$iw$C
    
    scala>   println(TypeAB)
    <console>:8: error: not found: value TypeAB
                    println(TypeAB)
                            ^
    
    scala> classOf[TypeAB]
    <console>:11: error: class type required but A with B found
                  classOf[TypeAB]
    

    有趣的是,Scala 确实设法匹配with in case 构造。

    【讨论】:

      【解决方案2】:

      Scala 通过 traits 支持多重继承。任何类都可以扩展 0 或 1 个类,但也可以“混合”任意数量的特征。 (有一点编译器的魔力可以重新排列幕后的东西以符合 JVM 的限制)语法类似于

      class MyClass extends [ClassOrTrait] with [Trait] with [AnotherTrait] with ...
      

      所以你的C类定义更像

      class ((C extends A) with B) 比喜欢class (C extends (A with B))

      A with B是一个类型,可以作为类型别名,但是classOf方法要一个类:

      scala> type AB = A with B
      defined type alias AB
      
      scala> classOf[AB]
      <console>:11: error: class type required but A with B found
                    classOf[AB]
                            ^
      

      scala> class AB extends A with B
      defined class AB
      
      scala> classOf[AB]
      res12: Class[AB] = class AB
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-06-13
        • 1970-01-01
        • 2021-08-25
        • 1970-01-01
        • 2012-03-18
        • 1970-01-01
        • 2017-04-06
        相关资源
        最近更新 更多