Last active
July 6, 2018 18:12
-
-
Save Jacoby6000/9a46a31ca11dd3f49601208dd720a65d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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: |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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]) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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