有没有办法扩展对象? [英] Is there any way to extend an object?

查看:61
本文介绍了有没有办法扩展对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在scala中,我们不能扩展object:

In scala, we cannot extend object:

object X 
object Y extends X

给出错误 error: not found: type X

在我的例子中,有人在一个对象中定义了一些功能,我需要扩展它(基本上是添加另一个方法).扩展此对象的最简单方法是什么?

In my case someone has defined some functionality in an object and I need to extend it (basically add another method). What would be the easiest way to extend this object?

推荐答案

正确答案通常取决于实际业务需求.从某个对象扩展在某种意义上会违背该对象的目的,因为它不再是单例.

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
}

这篇关于有没有办法扩展对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆