使用函数委托增强类的方法 [英] Way to enhance a class with function delegation

查看:35
本文介绍了使用函数委托增强类的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Scala 中有以下类:

I have the following classes in Scala:

class A {
    def doSomething() = ???

    def doOtherThing() = ???
}

class B {
    val a: A

    // need to enhance the class with both two functions doSomething() and doOtherThing() that delegates to A
    // def doSomething() = a.toDomething()
    // def doOtherThing() = a.doOtherThing()
}

我需要一种在编译时增强类 B 的方法,它具有与 A 相同的函数签名,在 B 上调用时只需委托给 A.

I need a way to enhance at compile time class B with the same function signatures as A that simply delegate to A when invoked on B.

在 Scala 中有没有一种很好的方法可以做到这一点?

Is there a nice way to do this in Scala?

谢谢.

推荐答案

在 Dotty(以及未来的 Scala 3)中,它是 现在可用就像

In Dotty (and in future Scala 3), it's now available simply as

class B {
    val a: A

    export a
}

导出a.{doSomething, doOtherThing}.

对于 Scala 2,遗憾的是没有内置解决方案.正如蒂姆所说,你可以做一个,但你需要决定你愿意付出多少努力以及具体支持什么.

For Scala 2, there is unfortunately no built-in solution. As Tim says, you can make one, but you need to decide how much effort you are willing to spend and what exactly to support.

这篇关于使用函数委托增强类的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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