Kotlin类型不匹配,必填:x找到:x? [英] Kotlin Type mismatch, required: x found: 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)
}
这是正确的方法
推荐答案
简短答案:是.
这意味着编译器不确定是否为s.th.是!=null
.如果您确定它不为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屋!