3

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)

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

My apologies if the question wasn’t clear. I added a link to my code in the question.
@rightfold: Check my ideone. Not sure it captures the spirit of what you're going for, but it's pretty similar to how I approach the problem. I'm not a super experienced Scala dev, but I've found so far that whenever I've thought I needed to reach for self-types and structural type annotations, there's a simpler answer, at least for the basic cases.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.