Scala self type can it be compiled when using `extends`?

I am looking at scala type annotations of type types

he says he new Service

cannot be created because of use self type

in favor extends

. But I tried the example also with extends

and it still doesn't 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 Service ^

Am I missing something? why does it claim that with extension it should compile? it doesn't compile ...

+3


source to share


1 answer


A characteristic like extending an interface in java cannot be created directly. you need to subclass it, which you do by adding {}.

So you need to do



new Service {}

      

and you are not instantiating the service, but an "anonymous class" that extends the service characteristic

+3


source







All Articles