DZone
Java Zone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
  • Refcardz
  • Trend Reports
  • Webinars
  • Zones
  • |
    • Agile
    • AI
    • Big Data
    • Cloud
    • Database
    • DevOps
    • Integration
    • IoT
    • Java
    • Microservices
    • Open Source
    • Performance
    • Security
    • Web Dev
DZone > Java Zone > Scala's Self Type Annotations

Scala's Self Type Annotations

This overview covers self type annotations/references in Scala and their usefulness for dependency injection while also touching on the cake pattern that uses them.

Anuj Saxena user avatar by
Anuj Saxena
·
May. 18, 17 · Java Zone · Tutorial
Like (12)
Save
Tweet
15.03K Views

Join the DZone community and get the full member experience.

Join For Free

Self type annotations/references allow you to redefine this and is a way to declare the dependencies required by a component. Using a trait mixin, you can inject various implementations of dependencies.

In layman terms, self type annotations/references are to ensure that the class cannot be instantiated without mixing in the trait explicitly specified in the notation, and its members can be used in the class exactly like extending/mixing in a trait.

The syntax goes like this:

trait A{
    ...some defs and vals
}

class B{
    this: A =>
    .....rest of the class
    .....here we can use def and vals of A too
}


In this example, if we try to instantiate our class B, it won’t:

val b = new B //gives error: class B cannot be instantiated because it does not conform to its self-type B with A


It needs A to be mixed in to be instantiated:

val b = new B with A


Now, what’s “this: A =>”

It's the self type annotation, and you can use ‘self’ or any identifier instead of ‘this’ (more details). Using A here means class B started with mixing in trait A.

Problem

The point here is the advantage that we get from using self types instead of mixing in a trait. So let's consider the following snippet that displays a class extending a trait:

trait ReaderWriter{
    def read: String = "data from file"
    def write: String = "written to a file"
}
class Service extends ReaderWriter
    def reading = read()
    def writing = write()
}
val service = new Service


The problem here is that we are stuck with the ReaderWriter trait forever in case of class Service. We can’t change the extended trait without changing our class definition

Solution

Now here, we’ll use self type annotation:

trait ReadWrite{
    def read: String = "data from file"
    def write: String = "data written to file"
}
class Service{
    this: ReaderWriter =>
    def reading: String = read()
    def writing : String = write()
}


We can instantiate our class Service by mixing in ReadWrite:

val service = new Service with ReadWrite


Now if some trait ReadWriteDB extends ReaderWriter...

trait ReadWriteDB extends ReadWrite {
    def read: String = "data from DB"
    def write: String = "data written to DB"
}


... then we can instantiate our service class with ReadWriteDB:

val service = new Service with ReadWriteDB


Hence we can mixin child traits explicitly specified in class definitions at the time of instantiation.

Using Multiple Traits in Self References

One more trait:

trait UpdateDelete{
    def update: String = "update file data"
    def delete: String = "deleted data from file"
}


Now the new class definition

class Service{
    this: ReadWrite with UpdateDelete =>
    .....class definition
}


Class instantiation

val service = new Service with ReadWrite with UpdateDelete


So that was it for self type annotations/references.

Usage

Self type annotations/references are used in cake patterns, which we didn't cover above. The cake pattern is a means of dependency injection, along with the Constructor Pattern and Google Guice. We’ll discuss those future posts.

Hope it was helpful!

Self (programming language) Annotation Trait (computer programming)

Published at DZone with permission of Anuj Saxena, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • How To Check for JSON Insecure Deserialization (JID) Attacks With Java
  • Spring, IoC Containers, and Static Code: Design Principles
  • How to Build Microservices With Node.js
  • Major PostgreSQL Features You Should Know About

Comments

Java Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • MVB Program
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends:

DZone.com is powered by 

AnswerHub logo