venkats / devoxxpl2019

3 stars 4 forks source link

Part 4 solution without Truck.(Truck) #1

Open jigga opened 5 years ago

jigga commented 5 years ago

So I'm trying to wrap my head around lambdas with receiver and actually have just discovered that the function type for the block argument of the operate function don't have to be Truck.(Truck) -> Unit, but can simply be (Truck) -> Unit. Here's my working solution:

val left = "left"
val right = "right"
val straight = "straight"

object Truck {

  private val actions = StringBuilder()

  infix fun turns(dir: String) {
    actions.append(" turned $dir")
  }

  infix fun drives(dir: String) {
    actions.append(" drives $dir")
  }

  infix fun operate(action: (Truck) -> Unit) {
    print("Truck")
    action(this)
    println(actions.toString())
  }
}

Truck operate { truck ->
  truck turns left
  truck drives straight
  truck turns right
}

Any thoughts on that?

Thanks, Arek

venkats commented 5 years ago

Hi Arek,

The truck -> can be removed and truck can be replaced with it.

The only disadvantage of this solution is that left, right, and straight are in the package level instead of being within the Truck object.

Regards,

Venkat