Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import scala.reflect.{classTag, ClassTag}
object Injector {
private val rootInjector = new Injector(None)
def createInjector = rootInjector.createChild(rootInjector)
def mapValue[T:ClassTag](instance:T): Unit =
rootInjector.mapValue[T](instance)
}
class Injector(val parent:Option[Injector]) {
private val valueMap =
scala.collection.mutable.Map[ClassTag[_], Any]()
def clear = valueMap.clear
def createChild:Injector = new Injector(Some(this))
def createChild(parent:Injector):Injector = new Injector(Some(parent))
private def hasInjectedValue(cTag:ClassTag[_]):Boolean = {
valueMap.get(cTag) match {
case Some(_) => true
case None => false
}
}
def mapValue[T:ClassTag](instance:T): Unit = {
valueMap += classTag[T] -> instance
}
def getInstance[T:ClassTag]: T =
valueMap.get(classTag[T]) match {
case Some(i) => i.asInstanceOf[T]
case None => {
parent match {
case Some(j) => j.getInstance[T]
case None => throw new Error("no injected target error")
}
}
}
}
trait Inject {
var injector:Injector = Injector.createInjector
def injected[T:ClassTag]: T = injector.getInstance[T]
}
trait CustomInject {
val injector:Injector
def injected[T:ClassTag]: T = injector.getInstance[T]
}
//simple injection test
class A(val x:Int)
class B
// Injector
class C extends Inject {
val a: A = injected[A]
val b: B = injected[B]
def run: Unit = println(a.x, b)
}
Injector.mapValue(new A(4))
Injector.mapValue(new B)
val c = new C
c.run
class D extends CustomInject {
val injector = Injector.createInjector
val a: A = injected[A]
val b: B = injected[B]
def run: Unit = println(a.x, b)
}
val d = new D
d.run
// 本当はこういう風に書きたい
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment