public
Last active

Simple Scala DI

  • Download Gist
README.md
Markdown

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

curl -ks https://gist.github.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.

di.scala
Scala
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
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
}
di.sh
Shell
1 2 3 4 5 6 7 8 9
#!/bin/bash
tmpdi=$(mktemp -d XXXXXXX) || exit $?
[ "${tmpdi}" ] || exit 1
trap "rm -rf ${tmpdi}" 0 1 2 3
(
cd ${tmpdi} || exit 1
curl -ksO https://gist.github.com/nicerobot/5203624/raw/di.scala
scalac di.scala && scala -cp . org.nicerobot.di.DiExample
)
output.txt
1 2 3 4 5 6 7 8 9 10 11
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)))

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.