将参数传递给Kotlin中的函数

时间:2019-02-18 21:03:07

标签: android kotlin

这是我的活动:

class PlayerDetails : AppCompatActivity(), View.OnClickListener {
    ...
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_player_details)
        val intent = getIntent()
        numOfPlayers = intent.getIntExtra("number_of_players", 1)
        next_details.setOnClickListener(this)
    }

    override fun onClick(v: View?) {
        for (i in 1..numOfPlayers) {
                ...
                nextUser()

            } else {
                blankFields()
            }

        }
    }
    private fun nextUser() {

    }

}

如何在for循环中将i的值传递给nextUser()

我尝试了nextUser(num: Int = i),但是没有用。

有什么主意吗?

3 个答案:

答案 0 :(得分:0)

更改您的方法以接受参数

private fun nextUser(num: Int) { }

并这样调用函数

for (i in 1..numOfPlayers) { ... nextUser(i) } else { blankFields() } }

答案 1 :(得分:0)

您的nextUser应该如下所示:

private fun nextUser(i: Int = DEFAULT_VALUE) {

}

DEFAULT_VALUE是可选的,如果您选择可以从函数定义中删除= DEFAULT_VALUE。在这种情况下,致电nextUser时始终需要传递值。

然后,可以在for循环中按如下所示将i的值传递给nextUser

for (i in 1..numOfPlayers) {
    ...
    nextUser(i)

} else {
    blankFields()
}

答案 2 :(得分:0)

NextUser()函数必须接受一个输入参数。

现在代码就像

for(i until numOfPlayers) {
   nextuser(i)
}
else {
   blankFields()
}

现在nextUser看起来像。

nextUser(value : Int) {
    TODO("perform the action")
}