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

时间:2016-07-26 09:13:43

标签: android android-layout generics delegates kotlin

我有这个代码。它将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
}

有什么方法可以删除惰性块中view<ImageView>之类的内容view吗?我可以在函数view()中获取或推断属性的类型吗?

1 个答案:

答案 0 :(得分:5)

你可以拥有

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

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

请注意,在这两种情况下,backgroundImage的类型都是从右侧表达式类型推断出来的。