scala 隐式构造函数参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18562735/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 05:37:29  来源:igfitidea点击:

Implicit constructor parameters

scala

提问by Nozdrum

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?

一切都很好,但是由于 this.world 是隐式的(我认为?)我不需要在那里指定它。我在这里做什么/理解错了?

回答by Marius Danila

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.

但是,createMap 方法必须执行一些副作用,因此在没有括号的情况下调用它并不是一件好事。

I suggest changing to:

我建议改为:

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

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

这样,您就可以保持原来的调用语法: createMap()

回答by Brandon Mott

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 {...}