安卓应用层

2018-06-30kotlin 实践

2018-06-30  本文已影响6人  honglei92

问题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)
             }
         }
上一篇 下一篇

猜你喜欢

热点阅读