Is there any way to extend an object?

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

提交回复
热议问题