iextensionunit类_Kotlin属性:“属性的类型参数必须在其接收器类型中使用”

I have the following simple Kotlin extension functions:

// Get the views of ViewGroup

inline val ViewGroup.views: List

get() = (0..childCount - 1).map { getChildAt(it) }

// Get the views of ViewGroup of given type

inline fun ViewGroup.getViewsOfType() : List {

return this.views.filterIsInstance()

}

This code compiles and works fine. But, I want the function getViewsOfType to be a property, just like the views. Android Studio even suggests it. I let AS do the refactoring and it generates this code:

inline val ViewGroup.viewsOfType: List

get() = this.views.filterIsInstance()

But this code doesn't compile. It causes error: "Type parameter of a property must be used in its receiver type"

What is the issue here? Searching for help on this error doesn't seem to lead to an answer.

解决方案

The error means that you can only have a generic type parameter for an extension property if you're using said type in the receiver type - the type that you're extending.

For example, you could have an extension that extends T:

val T.propName: Unit

get() = Unit

Or one that extends a type that uses T as a parameter:

val List.propName: Unit

get() = Unit

As for why this is, I think the reason is that a property can't have a generic type parameter like a function can. While we can call a function with a generic type parameter...

val buttons = viewGroup.getViewsOfType()

... I don't believe a similar syntax exists for properties:

val buttons = viewGroup.viewsOfType // ??

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值