1

Is there a way to instantiate an abstract type with an object in Scala? What I mean is something like this:

trait Processor {
  /* 1. defining a type shortcut */
  type ProcessorType = RequestTrait with ResponseTrait

  /* 2. defining a method with default implementation */
  def retry = new ProcessorType {
    override def retry = None
  }
  /* 3. Compilation fails */
  def reRetry = new RequestTrait with ResponseTrait {
    override def retry = None
  }
  /* 4. This one works correctly */
}
Pavel
  • 11
  • 2

1 Answers1

1

The issue is that the withs in

type ProcessorType = RequestTrait with ResponseTrait

and

class X extends RequestTrait with ResponseTrait { ... }
new RequestTrait with ResponseTrait { ... }

are actually different. The first defines a compound type; the second doesn't, it just separates (optional) class and traits. And it only allows a class and traits, not arbitrary types. So new ProcessorType { ... } isn't legal.

This pun works because the class created by the second form is a subtype of all listed classes/traits and so of the compound type created by the first form, but it's still just a pun.

Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487