1.lambda
问题1: Lambda argument should be moved out of parentheses more... (Ctrl+F1)
在写onItemClickListener的时候,开始写的:
resourceList.setOnItemClickListener(object :AdapterView.OnItemClickListener{
override fun onItemClick(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) {
}
})
会提示:
Use property access syntax less... (Ctrl+F1)
This inspection reports calls to Java get and set methods that can be replaced with the use of Kotlin synthetic properties.
字面意思就是使用kotlin的综合属性替换。那我就用lambda替换。
第一次修改:
resourceList.setOnItemClickListener({ p0, p1, p2, p3 ->
Toast.makeText(context, p2.toString(), Toast.LENGTH_SHORT).show()
})
会提示:
Lambda argument should be moved out of parentheses less... (Ctrl+F1)
This inspection detects a lambda expression inside parentheses which can be moved outside of them.
意思是圆括号里面的lambda可以移出来。
第二次修改:
resourceList.setOnItemClickListener(){ p0, p1, p2, p3 ->
Toast.makeText(context, p2.toString(), Toast.LENGTH_SHORT).show()
}
会提示:
Remove unnecessary parentheses from function call with lambda less... (Ctrl+F1)
This inspection reports unnecessary parentheses of function calls where the only parameter is a lambda that's outside the parentheses.
意思是当函数参数只有一个在圆括号外面的lambda表达式的话,可以删除圆括号。
第三次修改:
resourceList.setOnItemClickListener{ p0, p1, p2, p3 ->
Toast.makeText(context, p2.toString(), Toast.LENGTH_SHORT).show()
}
另外一例:
mSortAdapter = object : SortAdapter(activity, list, { id: Int, position: Int ->
//判断是否已经初始化
if (::mSortDetailFragment.isInitialized == true) {
isMoved = true
targetPosition = position
setChedked(position, true)
}
}) {}
可以写成:
mSortAdapter = SortAdapter(activity, list) { _, position ->
//判断是否已经初始化
if (::mSortDetailFragment.isInitialized == true) {
isMoved = true
targetPosition = position
setChedked(position, true)
}
}
2.问答
1.var和val的区别:
var是一个可变变量,这是一个可以通过重新分配来更改为另一个值的变量。这种声明变量的方式和java中声明变量的方式一样。
val是一个只读变量,这种声明变量的方式相当于java中的final变量。一个val创建的时候必须初始化,因为以后不能被改变。