Create a gist now

Instantly share code, notes, and snippets.

@nicerobot /
Last active Dec 15, 2015

What would you like to do?
Simple Scala DI

In Scala, "DI" should stand for "Default/Implicit".

curl -ks | bash -

A simple type of dependency injection can be accomplished with default parameters. It is enhanced further with implicits.

It's not perfect. For example, implicits don't seem to cascade so the ones to inject have to be explicitly defined each time. But the primary reason for DI is to decouple code (while costing simplicity). I think this approach accomplishes the goal and with less complexity because it doesn't require any framework and relies on rudimentary Scala features.

package org.nicerobot.di
case class A(i:Int)
case class B(i:Int)
class C()(implicit a: A = new A(0), b: B = new B(0)) { override def toString = s"${super.toString}(${a}, ${b})" }
class D()(implicit b: B = new B(0), c: C = new C()) { override def toString = s"${super.toString}(${b}, ${c})" }
object DiExample extends App {
def run1()(implicit a: A) = {
println(new C())
println(new D())
def run2()(implicit b: B, c: C) = {
implicit val a = new A(3)
println(new C())
println(new D())
def run3()(implicit b: A) = {
implicit val b = new B(4)
println(new D())
def main = {
implicit val a = new A(1)
implicit val b = new B(2)
implicit val c = new C()
tmpdi=$(mktemp -d XXXXXXX) || exit $?
[ "${tmpdi}" ] || exit 1
trap "rm -rf ${tmpdi}" 0 1 2 3
cd ${tmpdi} || exit 1
curl -ksO curl -ks
scalac di.scala && scala -cp . org.nicerobot.di.DiExample
org.nicerobot.di.C@1f2d7680(A(1), B(0))
org.nicerobot.di.D@580e781f(B(0), org.nicerobot.di.C@1df06863(A(0), B(0)))
org.nicerobot.di.C@12554af0(A(1), B(2))
org.nicerobot.di.C@1daadbf7(A(3), B(2))
org.nicerobot.di.D@3c4f4458(B(2), org.nicerobot.di.C@12554af0(A(1), B(2)))
org.nicerobot.di.D@78100c56(B(4), org.nicerobot.di.C@659a1fae(A(0), B(0)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment