Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

215
Visualizações
Decorate by Delegation (like kotlin) in Scala

In kotlin there is 'Decorate by Delegation' pattern. Is there a way to achieve it in an elegant way in Scala.

Here is a kotlin code example:

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()

}
over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

In Scala 2, as far as I can tell, you cannot achieve this. It is however possible in Scala 3 with 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 })

(See scastie)

As you can see with export you don't even have to create a separate names class (though you could if you want to) nor you have to have any sort of subtyping relation between decorator and decoratee as long as the the result will have all the necessary definitions exported or implemented manually.

In Scala 2 (to my knowledge), the best you can count on is conversion of one data-type into another data type with similar schema, via libraries like Chimney. I am not aware though of any library making such conversion between classes that store behavior.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda