macwire
macwire copied to clipboard
Support the wirering of closures instead classes?
I'm not sure if this fits into the project's scope and if it's generally possible:
Instead of wiring classes, I like to wire/bind closures. This offers to provide the interface design within the constructor or even plain functions, without the knowledge of the implementation.
It is very lightweight.
Could you maybe provide an example with a use-case?
Yes, of course. So, instead of using dependency Objects I like to define function pointers:
class Test(calcWorldPos: (Int, Int) => (Double, Double)) {
val pos = calcWorldPos(10,200)
}
This interface is very lightweight. No traits are required and I can "wire" any library function quite easy:
object PosConversion{
def screenToWorldPos(x:Int,y:Int):(Double,Double) = ???
}
val t = new Test(PosConversion.screenToWorldPos)
Hey @staeff777 !
Do you want to achieve something like this?
class Test(calcWorldPos: (Int, Int) => (Double, Double)) {
val pos = calcWorldPos(10, 200)
}
object PosConversion {
def screenToWorldPos(x: Int, y: Int): (Double, Double) = (0.0, 0.0)
}
val t = new Test(PosConversion.screenToWorldPos)
//this must be in scope in order to be considered as dependency to be used when wiring
val f: (Int, Int) => (Double, Double) = PosConversion.screenToWorldPos
val tWired = wire[Test]
tWired.pos mustBe (0.0, 0.0)
This looks good. I tried the code, changed tWired to a lazy val, the compiler / macro sais "Error:(16, 24) Found multiple values of type [(Int, Int) => (Double, Double)]: [List(get$$instance$$f, f)] lazy val tWired = wire[Test]"
Maybe the overhead due to the in-scope requirement, makes this example not quite useful. (This might change, if wiring in combination with other dependency objects wants to be achieved.) Its a general decision if one wants to give up the readability for convenience.
This error sounds like you had two objects of the same type in scope. Are you shure that you have only added the 'lazy' word to the above example and not accidently doubled a line or something?
@staeff777 the error looks a bit suspicious ... could you paste an entire failing test which would demonstrate it?
You are right. It is working. I tried it in a Intellij Scala Workbook first. That was the problem.
it is also working with:
def f = PosConversion.screenToWorldPos _
Thank you very much.