处理谓词中返回的最佳方法

时间:2017-11-18 21:10:48

标签: kotlin

当我在谓词中返回一个函数时,编译器没有注册它并仍然抱怨

  

A'返回'具有块体的函数需要表达式

我找到的解决方案是在谓词之后抛出一个。

fun boo(): Int {
    sth.apply {
        return sthElse
    }
    throw Exception("Unkown View type")
}

我想知道是否有更优雅的方式。

p.s:实际的Android代码

override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): RecyclerView.ViewHolder {
    LayoutInflater.from(parent?.context)
            .inflate(R.layout.item_category_node, parent, false)
            .apply {
                return CategoryNodeViewHolder(this, this@CategoriesAdapter)
    }
    throw Exception("View type error")
}

3 个答案:

答案 0 :(得分:1)

编辑:看到你的例子后:

   override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int)
=  LayoutInflater.from(parent?.context)
            .inflate(R.layout.item_category_node, parent, false)
            .let {
                CategoryNodeViewHolder(this, this@CategoriesAdapter)
            }

答案 1 :(得分:1)

在这些情况下应使用'run'扩展功能。根据{{​​3}} 运行

  

调用指定的功能块并返回其结果。

我的代码现在看起来像这样

override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): RecyclerView.ViewHolder {
      return LayoutInflater.from(parent?.context)
            .inflate(R.layout.item_category_node, parent, false)
            .run {
                 CategoryNodeViewHolder(this, this@CategoriesAdapter)
            }
    //throw Exception("Unkown View type")
}

答案 2 :(得分:0)

apply函数已经有一个被调用对象的return语句,请参阅https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/apply.html

override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int) =
   CategoryNodeViewHolder(
       LayoutInflater.from(parent?.context).apply{
       inflate(R.layout.item_category_node, parent, false) 
       }, this@CategoriesAdapter)

现在返回方法的正确对象类型,同时实例化layoutInflater,并在用于实例化CategoryNodeViewHolder之前应用CategoryNodeViewHolder所需的通胀。

相关问题