Skip to content

Instantly share code, notes, and snippets.

@edwinRNDR
Created November 3, 2018 18:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save edwinRNDR/18bacaf0fc51b44349c748eecbe76dde to your computer and use it in GitHub Desktop.
Save edwinRNDR/18bacaf0fc51b44349c748eecbe76dde to your computer and use it in GitHub Desktop.
Builder/DSL question
// -- this is a public function to make the creation of ColorBuffer instances simple
fun colorBuffer(width: Int, height: Int, contentScale: Double = 1.0, format: ColorFormat = ColorFormat.RGBa, type: ColorType = ColorType.UINT8): ColorBuffer {
return ColorBuffer.create(width, height, contentScale, format, type)
}
@Suppress("unused")
class RenderTargetBuilder(private val renderTarget: RenderTarget) {
// -- this is here to shadow the colorBuffer function that should not be used
@Deprecated("you should not use this", replaceWith = ReplaceWith("colorBuffer()"))
fun colorBuffer(width: Int, height: Int, contentScale: Double = 1.0, format: ColorFormat = ColorFormat.RGBa, type: ColorType = ColorType.UINT8): ColorBuffer {
throw IllegalStateException("use colorBuffer without width and height arguments")
}
// -- this is part of the DSL and this is what should be used
fun colorBuffer(colorBuffer: ColorBuffer) {
renderTarget.attach(colorBuffer)
}
// ..
}
fun renderTarget(width: Int, height: Int, contentScale: Double = 1.0, builder: RenderTargetBuilder.() -> Unit): RenderTarget {
val renderTarget = RenderTarget.create(width, height, contentScale)
RenderTargetBuilder(renderTarget).builder()
return renderTarget
}
fun main() {
// -- correct usage
val rt = renderTarget(640, 480) {
colorBuffer()
}
// -- incorrect usage, but an easy mistake to make
val ic = renderTarget(640, 480) {
colorBuffer(640, 480)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment