Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Yeah, Kotlin's solution is nice because it's so general: you can chain on to anything instead of needing everyone to implement a builder pattern.

And it's already idiomatic unlike bolting a pipeline operator onto a language that didn't start with it.



If you see somebody using a builder in Kotlin, they're basically doing it wrong. You can usually get rid of that stuff with a 1 line extension function (for example if it's some Java API that's being called).

  // extension function on Foo.Companion (similar to static class function in Java)
  fun Foo.Companion.create(block: FooBuilder.() -> Unit): Foo =
    FooBuilder().apply(block).build()

  // example usage
  val myFoo = Foo.create {
    setSomeproperty("foo")
    setAnotherProperty("bar")
  }
Works for any Java/Kotlin API that forces you into method chaining and calling build() manually. Also works without extension functions. You can just call it fun createAFoo(..) or whatever. Looking around in the Kotlin stdlib code base is instructive. Lots of little 1/2 liners like this.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: