简体   繁体   English

我可以推断委托中的属性类型吗?

[英]Can I infer type of a property in the delegate?

I have this code. 我有这个代码。 It will findViewById with a delegate. 它将找到带有委托的findViewById

val backgroundImage: ImageView by lazy { view<ImageView>(R.id.item_component_section_background) }

fun <T: View> view(id : Int) : T {
    val view : View = findViewById(id) ?: throw IllegalArgumentException("Given ID could not be found in current layout!")

    @Suppress("UNCHECKED_CAST")
    return view as T
}

Is there any way to remove the view<ImageView> for something like view in the lazy-block? 有什么办法可以删除lazy-block中的view之类的view<ImageView>吗? Can I get or infer the type of the property in the function view() ? 我可以在函数view()获取或推断属性的类型吗?

You can have 你可以有

val backgroundImage by lazy { view<ImageView>(R.id.imageView) }

or 要么

val backgroundImage by lazy<ImageView> { view(R.id.imageView) }

Note that in both cases the type of backgroundImage is inferred from the right hand side expression type. 请注意,在这两种情况下, backgroundImage的类型都是从右侧表达式类型推断出来的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么我不能使用“MutableState”作为属性委托? - Why can't I use `MutableState` as a property delegate? kotlin delegate属性,在get()方法中我如何访问该值? - kotlin delegate property ,In a get() method how i can access the value? Kotlin Jetpack Compose 了解 Delegate 属性中的类型 - Kotlin Jetpack Compose Understanding Type in Delegate property Rx Kotlin:map 函数无法推断返回类型 - Rx Kotlin: map function can't infer return type 我可以通过懒惰(委托)获得ParcelableExtra - Can I getParcelableExtra by lazy (delegate) 当返回通用类型 * 我得到错误没有足够的信息来推断类型变量 T - When returning Generic type * I get error not enough information to infer type variable T 无法推断 ArrayAdapter&lt;&gt; 的类型参数 - Cannot infer type arguments for ArrayAdapter<> findViewById 错误 - 没有足够的信息来推断类型变量 T。我复制了 java 代码并在线转换 - findViewById error - Not enough information to infer type variable T. I copied java code and converted it online Java到Kotlin转换后出现问题,Android Studio中出现错误,无法推断此参数的类型 - I have a problem after Java to Kotlin conversion with the error in Android Studio, Cannot infer a type for this parameter 此视图不受android studio的约束。 即使使用推断约束也看不到该按钮 - This view is not constrained android studio. I can not see the button even if I use Infer Constraints
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM