Kotlin 类型不匹配,需要:x 找到:x? [英] Kotlin Type mismatch, required: x found: x?

查看:35
本文介绍了Kotlin 类型不匹配,需要:x 找到:x?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现很多参数都有错误

I find a lot of arguments have the error

Type mismatch
required: FragmentActivity
found: FragmentActivity?

我不确定解决此问题的最佳方法是什么.目前,我将该行包装在一个变量中?.let{ statement }

I'm not sure of what's the best way to address this problem. Currently, I wrap the line in a variable?.let{ statement }

meViewModel = ViewModelProviders.of((iMainActivity as Fragment).activity, vmf).get(MeViewModel::class.java) }

进入

val fragmentActivity = (iMainActivity as Fragment).activity

fragmentActivity?.let 
{ 
   meViewModel = ViewModelProviders.of(fragmentActivity, vmf).get(MeViewModel::class.java) 
}

这是解决这个问题的正确方法

is it the right way to approach this

推荐答案

简短回答:是的.

这意味着编译器不确定 s.th.是 !=null.如果您确定它不为空,您还可以使用:

This means that the compiler is not sure if s.th. is !=null. If you are sure that it is not null you can also use:

val fragmentActivity = (iMainActivity as Fragment).activity!!

这给你 FragmentActivity 而不是 FragmentActivity? 并且你不需要 ?.let{}

That gives you FragmentActivity instead of FragmentActivity? and you dont need the ?.let{}

请记住,这可能会引发 NPE,而

Keep in mind that that might throw a NPE, while the

fragmentActivity?.let { fragment ->
   meViewModel = ViewModelProviders.of(fragment, vmf).get(MeViewModel::class.java) 
}

根本不会执行 .let{} 中的块,这通常比 NPE 危害小.请参阅 https://kotlinlang.org/docs/reference/null-safety.html 了解更多.

would simply not execute the block within .let{}, which is often less harmful then a NPE. See https://kotlinlang.org/docs/reference/null-safety.html for more.

这篇关于Kotlin 类型不匹配,需要:x 找到:x?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆