我们都知道链式编程,但今天所说的run就是应用于非链式的调用,非常适合用于给对象设置属性值,可以简化代码的编写。
以下举例说明:
不用run的情况:
val makeText = Toast.makeText(
this,
R.string.correct_toast,
Toast.LENGTH_SHORT
)
makeText.setGravity(Gravity.TOP,getScreenWidth()/2,0)
makeText.show()
在上面的情况下必须要定义一个中间变量makeText
才能解决问题,十分啰嗦
用run的情况:
Toast.makeText(this,
R.string.incorrect_toast,
Toast.LENGTH_SHORT)
.run {
setGravity(Gravity.TOP,-getScreenWidth()/2,0)
show()
}
在上面的情况下不需要定义一个中间变量makeText
就能解决问题