macwire icon indicating copy to clipboard operation
macwire copied to clipboard

Support the wirering of closures instead classes?

Open staeff777 opened this issue 8 years ago • 7 comments

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.

staeff777 avatar Apr 10 '17 20:04 staeff777

Could you maybe provide an example with a use-case?

adamw avatar Apr 10 '17 20:04 adamw

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)

staeff777 avatar Apr 12 '17 14:04 staeff777

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)

pawelpanasewicz avatar Apr 12 '17 18:04 pawelpanasewicz

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.

staeff777 avatar Apr 12 '17 20:04 staeff777

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?

pawelpanasewicz avatar Apr 13 '17 04:04 pawelpanasewicz

@staeff777 the error looks a bit suspicious ... could you paste an entire failing test which would demonstrate it?

adamw avatar Apr 13 '17 06:04 adamw

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.

staeff777 avatar Apr 14 '17 19:04 staeff777