Skip to content

Instantly share code, notes, and snippets.

@nicerobot
Last active December 15, 2015 04:39
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 nicerobot/5203624 to your computer and use it in GitHub Desktop.
Save nicerobot/5203624 to your computer and use it in GitHub Desktop.
Simple Scala DI

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

curl -ks  https://gist.githubusercontent.com/nicerobot/5203624/raw/di.sh | 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("\nrun1")
println(new C())
println(new D())
}
def run2()(implicit b: B, c: C) = {
println("\nrun2")
implicit val a = new A(3)
println(c)
println(new C())
println(new D())
}
def run3()(implicit b: A) = {
println("\nrun3")
implicit val b = new B(4)
println(new D())
}
def main = {
implicit val a = new A(1)
implicit val b = new B(2)
run1()
implicit val c = new C()
run2()
run3()
}
main
}
#!/bin/bash
tmpdi=$(mktemp -d XXXXXXX) || exit $?
[ "${tmpdi}" ] || exit 1
trap "rm -rf ${tmpdi}" 0 1 2 3
(
cd ${tmpdi} || exit 1
curl -ksO curl -ks https://gist.githubusercontent.com/nicerobot/5203624/raw/di.scala
scalac di.scala && scala -cp . org.nicerobot.di.DiExample
)
run1
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)))
run2
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)))
run3
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