user1804599
user1804599

Reputation:

Is it possible to define an unnamed trait and use it as a mixin in Scala?

I’ve implemented the cake pattern using structural types instead of wrapper traits. I am now wiring up my dependencies like this:

trait GreeterDependency { def greeter = HelloGreeter }
val printer = new Printer with GreeterDependency

It would be nice if I could do something like this instead:

val printer = new Printer with trait { def greeter = HelloGreeter }

However, I get a syntax error. Is there a way to define an unnamed trait and use it as a mixin like this?

(For clarity, here is all my code: http://ideone.com/vMDFYD)

Upvotes: 3

Views: 106

Answers (1)

acjay
acjay

Reputation: 36671

I'm not completely certain what you're going for, but I think what you're looking for is to instantiate a trait with its abstract members defined in an anonymous class. If that's the case, you can just do:

val printer = new Printer { def greeter = HelloGreeter }

It's a pattern I'm using a lot right now to make up for the fact that traits can't define constructor parameters.

Full refactoring based off of the Ideone link in the question:

trait Greeter {
  def apply(name: String): String
}

object HelloGreeter extends Greeter {
  def apply(name: String) = s"Hello, $name!"
}

trait Printer {
  def greeter: Greeter

  def apply(name: String) = println(greeter(name))
}

object Main extends App {
  val printer = new Printer { def greeter = HelloGreeter }
  printer("rightfold")
}

Running example here: http://ideone.com/mAumNY

Upvotes: 3

Related Questions