在 Scala 中通过委托装饰(如 kotlin)

Decorate by Delegation (like kotlin) in Scala

在 kotlin 中有“Decorate by Delegation”模式。有没有办法在 Scala 中以优雅的方式实现它。

这是一个 kotlin 代码示例:

interface Doo{
    fun a(): Unit
    fun b(): Unit
}

class Goo:Doo {
    override fun a() {
        println("goo a")
    }

    override fun b() {
        println("goo b")
    }
}

class Moo(doo: Doo):Doo by doo{
    override fun b() {
        println("mooooooo")
    }
}

fun main() {
    val m = Moo(Goo())
    m.a();m.b()

}

据我所知,在 Scala 2 中,您无法实现这一点。然而,在 Scala 3 中可以使用 export:

trait Foo {
  
  def a: Int
  
  def b: String
}

trait Bar {
  
  def a: Int
}

def decorateAsFoo(bar: Bar): Foo = new Foo {
  export bar._ // export all bar methods/values/types in this Foo impl
  
  override def b: String = "decorated"
}


decorateFoo(new Bar { override def a: Int = 10 })

(见scastie

正如您在 export 中看到的那样,您甚至不必创建单独的名称 class(尽管您可以根据需要创建),也不必具有任何类型的子类型关系在装饰者和装饰者之间,只要结果将导出或手动实现所有必要的定义。

在 Scala 2 中(据我所知),您可以指望的最好方法是通过像 Chimney 这样的库将一种数据类型转换为具有相似模式的另一种数据类型。我不知道有任何库在存储行为的 类 之间进行这种转换。