Is there any way to extend an object?

前端 未结 6 824
礼貌的吻别
礼貌的吻别 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:35

    As so often the correct answer depends on the actual business requirement. Extending from an object would in some sense defy the purpose of that object since it wouldn't be a singleton any longer.

    What might be a solution is to extract the behavior into an abstract trait. And create objects extending that trait like so:

    trait T{
        // some behavior goes here
    }
    
    object X extends T
    
    object Y extends T {
        // additional stuff here
    }
    
    0 讨论(0)
  • 2020-12-05 06:39

    The only way to share code between two objects is by having one or more common superclass/trait.

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-12-05 06:55

    You can't actually extend an object, because that would create two of it, and an object by definition exists only once (edit: well, that's not quite true, because the object definition can be in a class or method).

    For your purposes, try this:

    object X {
    }
    
    object Y {
        def a = 5
    }
    
    implicit def xToY(x: X.type) = Y
    
    println(X.a)
    

    It doesn't actually extend, but it does allow you to call new methods on it than were originally defined.

    0 讨论(0)
  • 2020-12-05 06:56

    If you want use methods and values from another object you can use import.

    object X{
      def x = 5
    }
    
    object Y{
      import X._
      val y = x
    }
    
    0 讨论(0)
  • 2020-12-05 07:02

    You can convert parent into class + companion object, and then have child extend class E.g.

    in Parent.scala

    class Parent {}
    
    object Parent extends Parent {}
    

    And then in Child.scala

    object Child extends Parent {}
    

    Yes, it's more a hack than a solution.

    0 讨论(0)
提交回复
热议问题