Tuesday, 15 September 2015

libgdx - What's the correct way to handle uninstantiated class variables in Scala? -



libgdx - What's the correct way to handle uninstantiated class variables in Scala? -

so, scala deviates java in way handles fields. java way define them, instantiate them in constructor. understand it, scala both in constructor. however, i'm extending java class things quite differently, part of game development framework libgdx. code looks this:

class helloworld extends game { private var batch: spritebatch = null private var font: bitmapfont = null override def create(): unit = { batch = new spritebatch font = new bitmapfont font.setcolor(color.red) } override def dispose(): unit = { batch.dispose() font.dispose() } override def render(): unit = { gdx.gl.glclearcolor(1, 1, 1, 1) gdx.gl.glclear(gl20.gl_color_buffer_bit) batch.begin() font.draw(batch, "hello, world!", 200, 200) batch.end() } }

because class has no true constructor , instead created using create, can't create variables in create , have them visible other methods, leading me how i've done here. however, forces me utilize vars when should vals. missing something? there improve way this, or since i'm working java-specific framework has wonky?

edit: forgot mention, can't like

private val batch = new spritebatch

because can't phone call libgdx's object constructors until after it's initialised (and can subsequently phone call create).

maybe can write more scala-friendly wrapper around java api?

trait scalagame { def dispose() def render() } class gamewrapper(creategame: => scalagame) extends game { lazy val game = creategame override def create() { game } override def dispose() = game.dispose() override def render() = game.render() }

and then:

class helloworld extends scalagame { private val batch: spritebatch = new spritebatch private val font: bitmapfont = new bitmapfont font.setcolor(color.red) override def dispose(): unit = { batch.dispose() font.dispose() } override def render(): unit = { gdx.gl.glclearcolor(1, 1, 1, 1) gdx.gl.glclear(gl20.gl_color_buffer_bit) batch.begin() font.draw(batch, "hello, world!", 200, 200) batch.end() } } val game = new gamewrapper(new helloworld)

scala libgdx

No comments:

Post a Comment