5.0 操作符重载

简化前面的的天气列表的例子,在ForecastList.kt这个类中,实现一个get方法,还有一个size方法:

data class ForecastList(val city: String, val country: String, val dailyForecast: List) {
    operator fun get(position: Int): Forecast = dailyForecast[position]
    fun size(): Int = dailyForecast.size
}

然后在我们的adapter类中,我们可以写得更简单一点

class ForecastListAdapter(val weekForecast: ForecastList) : RecyclerView.Adapter() {
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        return ViewHolder(TextView(parent.getContext()))
    }
    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
//        with(weekForecast.dailyForecast[position]) {
//            holder.textView.text = "$date - $description - $high/$low"
//        }
        with(weekForecast[position]) {
            holder.textView.text = "$date - $description - $high/$low"
        }
    }
//    override fun getItemCount(): Int = weekForecast.dailyForecast.size
    override fun getItemCount(): Int = weekForecast.size()
    class ViewHolder(val textView: TextView) : RecyclerView.ViewHolder(textView)
}

将dailyForecast的每一项对应的赋值给ForecastList,在外部访问ForecastList的item时,实际获取的是dailyForecast的item。size方法也是一样。

扩展函数的操作符

定义ViewGroup的扩展函数get,使其可以直接访问ViewGroup中的子view

operator fun ViewGroup.get(position: Int): View = getChildAt(position)

现在真的可以非常简单地从一个 ViewGroup 中通过position得到一个view

val container: ViewGroup = find(R.id.container)
val view = container[2]

你可能感兴趣的:(5.0 操作符重载)