Last active
May 9, 2017 00:05
-
-
Save Quar/b87900b27a2f408659474405b2da8ab4 to your computer and use it in GitHub Desktop.
Self Reference Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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