Is there any way to extend an object?

前端 未结 6 858
礼貌的吻别
礼貌的吻别 2020-12-05 06:29

In scala, we cannot extend object:

object X 
object Y extends X

gives an error error: not found: type X

I

6条回答
  •  悲&欢浪女
    2020-12-05 06:52

    Note that with Dotty (foundation of Scala 3), you can alternatively use composition (instead of inheritance) via export clauses which allow defining aliases for selected members of an object:

    object X { def f = 5 }
    
    object Y {
      export X._
      def g = 42
      def h = f * g
    }
    
    Y.f // 5
    Y.g // 42
    Y.h // 210
    

    Note that you can also restrict which members you want to export:

    object X { def f = 5; def g = 6 }
    object Y { export X.f }
    Y.f // 5
    Y.g
    ^^^
    value g is not a member of Y
    

提交回复
热议问题