【问题标题】:how to cast class to ((Int,String) -> Unit ) in kotlin [closed]如何在kotlin中将类转换为((Int,String)-> Unit)[关闭]
【发布时间】:2021-04-08 13:39:23
【问题描述】:

在 Kotlin 中,我可以在 (Int,String) -> Unit 类中实现这个 Invokable ((Int,String) -> Unit ) 没有写接口,但我需要将对象从另一个类中转换为这个 Invokable 类型。

【问题讨论】:

  • 在您的 sn-p 中,您已经匿名实现了 OnClickListener。您无需实现 Invokeable 接口。您可以拥有一个名为 foo 的函数并在您拥有该演员表的地方执行 context.foo(...)

标签: java android kotlin


【解决方案1】:

您忘记了要转换的函数类型的返回值。您可能应该进行安全强制转换,以便提供适当的错误消息,以便在遇到问题时更轻松地进行调试。

(context as? (Int, MenuItem) -> Unit)?.invoke(position - 1, menuItem) 
    ?: error("Failed to pass Activity with appropriate invoke function")

只是我的意见,但我认为为了代码清晰,接口是比实现函数类型更好的选择。

【讨论】:

  • 谢谢你的回答,你能解释一下为什么你更喜欢这种工具的界面
  • 主要是因为你的函数可以有一个有意义的名字。但是您也可以使用具有不同名称的函数实现多个接口,否则这些函数将具有相同的签名。如果您在没有接口的情况下执行此操作,则只能使用一种允许的实现。
【解决方案2】:

它的高阶函数或函数作为参数和转换使用关键字“is”用于检查实例,“as”用于直接转换

您的适配器如下所示:

CommonListAdapter(val mList: MutableList<Any>,
                  val onClick: (item: Any) -> Unit) : RecyclerView.Adapter<RecyclerView.ViewHolder>()

现在你的观点

adapter = CommonListAdapter(arrayListOf()) {
            val bundle = Bundle()
            if (it is StateItem) {
                bundle.putParcelable(StateItem::class.simpleName, it)
            } else if (it is LgaItem) {
                bundle.putParcelable(LgaItem::class.simpleName, it)
            } 
            val intent = Intent().putExtras(bundle)
            setResult(Activity.RESULT_OK, intent)
            finish()
}
binding.recyclerView.adapter = adapter

使用以下链接了解更多详情。

Higher Order Functions Type Casting

【讨论】:

    猜你喜欢
    • 2022-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-31
    • 2014-08-09
    • 1970-01-01
    • 2013-10-31
    相关资源
    最近更新 更多