Skip to content

Instantly share code, notes, and snippets.

@Jacoby6000
Last active July 6, 2018 18:12
Show Gist options
  • Save Jacoby6000/9a46a31ca11dd3f49601208dd720a65d to your computer and use it in GitHub Desktop.
Save Jacoby6000/9a46a31ca11dd3f49601208dd720a65d to your computer and use it in GitHub Desktop.
trait MathProvider[A] {
def plus(a: A, b: A): A
def minus(a: A, b: A): A
def divide(a: A, b: A): A
def multiply(a: A, b: A): A
}
trait AbstractMathProviderFactory {
def numericMathProvider[A: Numeric]: MathProvider[A]
}
class AbstractMathProviderFactoryImpl extends AbstractMathProviderFactory {
def numericMathProvider[A: Numeric]: MathProvider[A] =
new MathProvider[A] {
def plus(x: A, y: A): x + y
def minus(x: A, y: A): x - y
def divide(x: A, y: A): x / y
def multiply(x: A, y: A): x * y
}
}
class AbstractMathProviderFactory(n:
class MathProviderFactoryProxyBean(factory: AbstractMathProviderFactory, existingFactories: mutable.Map[TypeTag[_], _]) extends AbstractMathProviderFactory {
private val mathProviders: mutable.Map[TypeTag[_], _] = existingFactories
private def getOrSet[A: TypeTag](newA: => A): A =
mathProviders.getOrElse(implicitly[TypeTag[A]], {
mathProviders += (implicitly[TypeTag[A]] -> newA)
}).asInstanceOf[A]
def numericMathProvider[A: Numeric: TypeTag]: A = getOrSet(MathProviderFactory.numericMathProvider[A])
}
def add(x: Int, y: Int)(provider: MathProvider[Int]): Int =
provider.plus(x,y)
val proxy = new MathProviderFactoryProxyBean(new AbstractMathProviderFactoryImpl, mutable.Map.empty)
add(10, 11)(proxy.numericMathProvider)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment