ReadOnlyProperty-类型参数自动推断未验证界限
我正在尝试使用关键字将值注入class属性。
在下面实施代码没有问题。
open class Component
class ComponentA: Component()
class Equipment(val components: List<Component>) {
inline fun <reified T> getComponent(): T? {
return components.firstOrNull { it is T } as T?
}
val ca: ComponentA by find<ComponentA>() //this is what I intend to do
val ca1: List<ComponentA> by find() //no error or warning
val ca2 by find<List<ComponentA>>() //Error: Type argument is not within its bounds
}
inline fun <reified T> find(): ReadOnlyProperty<Equipment, T> where T : Component {
return ReadOnlyProperty { ref, _ -> ref.getComponent<T>() ?: throw Exception("Not found") }
}
但是我发现 val ca1:list&lt; componenta&gt;通过查找()
未显示任何错误或警告。当我尝试 val ca2 by find&lt; list&lt; componenta&gt;()
时,错误仍然正常显示。
任何人都可以解释为什么会发生这种情况以及如何确保 ca1 定义语法无效。
我正在使用:
- AUDVENOPENJDK 11.0.7.10热点
- Kotlin 1.6.21
- Intellij Ideas 2021.3.2
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好吧,我认为问题是来自编译器的想法,我尝试使用
viewModels()
与list而不是viewModel这样的android函数,我也遇到了相同的问题,这个想法不会显示任何错误:但是,当您编译代码时,您会收到一个错误:
这样您就可以忽略这个想法,这只是这个想法的问题,您的代码中也有一些错误
,代码> val组件:list&lt;设备&gt; 这应该是
val组件:list&lt;组件&gt;
return components.firstornull {它是t
,这应该是retode> retocer components.firstornull {它是t?
,因为您是因为您无法将NULL类型施放为非零类型,因此您的代码应该看起来像这样:
well I think the problem is from IDEA with the compiler, I tried using android functions like
viewModels()
with List instead of ViewModel and I had the same problem, the IDEA will not show any error:but when you compile the code you will get an error:
so you can ignore this, it's just a problem with the IDEA, also you have some mistakes in your code,
val components: List<Equipment>
this should beval components: List< Component >
return components.firstOrNull { it is T } as T
and this should bereturn components.firstOrNull { it is T } as T?
because you cannot cast a null type to a non-null typeso your code should look like this: