3
votes

I'm looking at scala types of types self types annotation

it says that new Service cannot be instantiated because of the usage of self type in favor of extends. But I tried the example also with extends and it still does not compile.

class TryMe {
  class ServiceInModule {
    def doTheThings() = "dfdf"
  }
  trait Module {
    lazy val serviceInModule = new ServiceInModule
  }

  trait Service extends Module {
    def doTheThings() = serviceInModule.doTheThings()
  }

  trait TestingModule extends Module {

  }

  new Service
}

Error:(22, 3) trait Service is abstract; cannot be instantiated new Service ^

Am I missing something? why does it claim that with extends it should compile? it does not compile...

1
just do new Service {}Eugene Zhulenev
@EugeneZhulenev thanks can you please post this as the answer?Jas

1 Answers

3
votes

A trait is like an enhances interface in java, it cannot be created directly. you need to subclass it, which is what you do by adding {}.

So you need to do

new Service {}

and you are creating not an instance of Service, but "anonymous class" that extends Service trait