我正在阅读有关数据连接的android文档https://developer.android.com/topic/libraries/data-binding/?hl=en,发现了这一点:
科特琳
findViewById<TextView>(R.id.sample_text).apply {
text = viewModel.userName
}
Java
TextView textView = findViewById(R.id.sample_text);
textView.setText(viewModel.getUserName());
我想知道为什么在kotlin中使用apply
而不是text(aka setText)
函数吗?
答案 0 :(得分:2)
findViewById<TextView>(R.id.sample_text).apply {
text = viewModel.userName
}
上面的代码等同于
val textView = findViewById<TextView>(R.id.sample_text)
textView.text = viewModel.userName
apply函数是作用域函数。它的主要用例是initialization of objects和Builder-style usage of methods that return Unit
fun arrayOfMinusOnes(size: Int): IntArray {
return IntArray(size).apply { fill(-1) }
}