Scala / Dotty - Mix a trait into an EXISTING object

Viewed 253

Is there a way to mix a trait into an existing object in either Dotty or Scala?

class SomeClass
trait SomeTrait

// This works, but it's not what I'm looking for:
new SomeClass with SomeTrait

// This is what I'm looking for, but it breaks:
val someClass = new SomeClass
someClass with SomeTrait

This answer provides a macro solution, but it's 7 years old, and I'm hoping (fingers crossed!) for something simpler.

3 Answers

Take a look at seemingly abandoned, but fairly recent, library zio-delegate:

import zio.delegate._

class SomeClass

trait SomeTrait {
  def test() = println("It just works!")
}

val someClass = new SomeClass

val result: SomeClass with SomeTrait =
  Mix[SomeClass, SomeTrait].mix(someClass, new SomeTrait {})

result.test()

It's still macro-based, and it's uncommon in Scala to use mixins to that degree. Zio changed to another pattern entirely, IIUC.

You still need a macro if you want class

class SomeClass1 extends SomeClass with SomeTrait

to be generated automatically.

I checked and the macro still works (with minor modifications)

def toPersisted[T](instance: T, id: Long): T with Persisted = macro impl[T]

def impl[T: c.WeakTypeTag](c: blackbox.Context)(instance: c.Tree, id: c.Tree): c.Tree = {
  import c.universe._

  val typ = weakTypeOf[T]
  val symbol = typ.typeSymbol
  if (!symbol.asClass.isCaseClass)
    c.abort(c.enclosingPosition, s"toPersisted only accepts case classes, you provided $typ")

  val accessors = typ.members.sorted.collect { case x: TermSymbol if x.isCaseAccessor && x.isMethod => x }
  val fieldNames = accessors map (_.name)

  val instanceParam = q"val instance: $typ"
  val idParam = q"${Modifiers(Flag.PARAMACCESSOR)} val id: Long"
  val superArgs = fieldNames map (fieldName => q"instance.$fieldName")
  val ctor =
    q"""def ${termNames.CONSTRUCTOR}($instanceParam, $idParam) = {
      super.${termNames.CONSTRUCTOR}(..$superArgs)
      ()
    }"""
  val idVal = idParam.duplicate
  val tmpl = Template(List(tq"$typ", tq"Persisted"), noSelfType, List(idVal, ctor))
  val cname = TypeName(c.freshName(symbol.name.toString + "$Persisted"))
  val cdef = ClassDef(NoMods, cname, Nil, tmpl)

  q"""
     $cdef
     new $cname($instance, $id)
    """
}

case class MyClass(i: Int, s: String)

val x = MyClass(1, "a")

val y = toPersisted(x, 2L)

y.i // 1
y.s // a
y.id // 2

What about using typeclasses instead?

From the example you provided in the comment to your question:

trait Organism
trait Winged[O <: Organism]
trait Legged[O <: Organism]

class Dog extends Organism
object Dog {
   implicit val legged: Legged[Dog] = new Legged[Dog] { ... }
}

class Fly extends Organism
object Fly {
   implicit val winged: Winged[Fly] = new Winged[Fly] { ... }
   implicit val legged: Legged[Fly] = new Legged[Fly] { ... }
}

This is a very flexible approach that allows you to either define the Legged and Winged properties when designing a particular organism, or add them later through implicits outside the respective companion objects. You can force an organism to always have legs/wings by providing the implicit in the companion object, or leave that up to users of your code.

You can then define

// Only Winged organisms (ie. `O` for which `Winged[O]` is available implicitly
def makeItFly[O <: Organism : Winged](o: O) 
Related