user2329125
user2329125

Reputation:

Implicit constructor parameters

So I tried to work with implicit parameters and variables for the first time and this is working perfectly fine

class Test(implicit val a: Int) {

    bar(5)

    def bar(c: Int)(implicit d: Int): Unit = {
        println(d)
    }
}

Then I tried it in some more complex code

class GameScreen(val game : Game)(implicit val batch: SpriteBatch, implicit val world: World, implicit val manager: AssetManager) extends Screen {

    val camera : OrthographicCamera = new OrthographicCamera

    createOpenGLStuff()
    createMap()

    def createMap(implicit w : World) : Unit = 
    {
    }

But now I get the error

- not enough arguments for method createMap: (implicit w: 
 com.badlogic.gdx.physics.box2d.World)Unit. Unspecified value parameter w.

I don't know why this is not working, i can write

createMap(this.world)

And all is well, but since this.world is implicit ( I think? ) I should not need to specify it there. What am I doing/understanding wrong here?

Upvotes: 13

Views: 13793

Answers (2)

Brandon Mott
Brandon Mott

Reputation: 61

Also, you only need the implicit keyword at the beginning of the parameter list:

class GameScreen(val game : Game)(implicit val batch: SpriteBatch, val world: World, val manager: AssetManager) extends Screen {...}

Upvotes: 3

Marius Danila
Marius Danila

Reputation: 10401

You need to drop the parens

class GameScreen(val game : Game)(implicit val batch: SpriteBatch, implicit val world:    World, implicit val manager: AssetManager) extends Screen {

  val camera : OrthographicCamera = new OrthographicCamera

  createOpenGLStuff()
  createMap //this works

  def createMap(implicit w : World) : Unit = 
  {
  }

However, the createMap method has to perform some side-effects, so calling it without parens isn't really a good thing.

I suggest changing to:

def createMap()(implicit w : World) : Unit = {
  ...
}

This way, you get to maintain the original calling syntax: createMap()

Upvotes: 13

Related Questions