When extending a trait within a trait, what does 'super' refer to?

后端 未结 3 2105
忘掉有多难
忘掉有多难 2021-02-19 05:34

I want to to extend a trait within a trait, like this:

  trait NodeTypes {
    trait Node {
      def allNodesHaveThis: Int
    }
  }

  trait ScrumptiousTypes e         


        
3条回答
  •  梦谈多话
    2021-02-19 06:03

    This is because of class lineraization. See Spec.

    Explanation

    Let C be a class with template C1 with ... with Cn. Then lineraization is concatenation of elements from Cn to C1, replacing all identical elements to left. Here elements include var, val, def, traits, object.

    If you want to see the order of linearization, use

    import scala.reflect.runtime.universe._
    val tpe = typeOf[scala.collection.immutable.List[_]]
    tpe.baseClasses foreach { s => println(s.fullName) }
    

    In your case, if you change the order from ScrumptiousTypes with YummyTypes to YummyTypes with ScrumptiousTypes, then error will be on method yumminess.

    An alternate to @余杰水 is to extend inner class like,

    case class Node() extends super[ScrumptiousTypes].Node with super[YummyTypes].Node 
    

提交回复
热议问题