Skip to content

Instantly share code, notes, and snippets.

@Quar
Last active May 9, 2017 00:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Quar/b87900b27a2f408659474405b2da8ab4 to your computer and use it in GitHub Desktop.
Save Quar/b87900b27a2f408659474405b2da8ab4 to your computer and use it in GitHub Desktop.
Self Reference Example
// continued the original example from
// https://scalerablog.wordpress.com/2015/07/13/traditionally-baked-scala-cake/
import scala.util.Random
trait MyComponent {
def service: MyService
trait MyService {
def saySomething:String
}
}
trait MyRepository {
def getRandomExpression(length:Int = 10): String = Random.nextString(length)
}
class MyComponentImpl extends MyComponent{
self: MyRepository =>
// note `self` can be other names, e.g. `selfies`
def service = new MyServiceImpl
class MyServiceImpl extends MyService {
def saySomething: String = MyComponentImpl.this.getRandomExpression()
}
}
object Main extends App {
val system = new MyComponentImpl with MyRepository
println(system.service.saySomething)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment