Kotlin 通用属性 [英] Kotlin Generic Property

查看:25
本文介绍了Kotlin 通用属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 kotlin 中有没有办法在不声明类级别的泛型类型的情况下创建泛型属性?看起来像这样的东西:

Is there a way in kotlin to create a generic property without declaring a class level generic type? Something that looks like this:

interface Generic {
    val t: T //I need this type only once, thats why I dont wanna pass in the class level

    fun <E> gMethod(e: E) { //This works, so I'm wondering if there's something similiar to properties

    }
}

推荐答案

自从关于泛型的文档 没有提到这样的事情,我很确定这不是语言的一部分.

Since the documentation about generics has no mention of such thing, I'm pretty sure this isn't a part of the language.

这很可能是因为您必须在某个点声明属性的类型.泛型函数是有意义的,因为您使用具有某种静态类型的参数来调用它们(或者在扩展函数的情况下,在这样的参数上调用它们).

This is most likely because you have to declare the type of the property at some point. Generic functions make sense, because you call them with arguments that have some sort of a static type (or in the case of extension functions, call them on such arguments).

问题是,您为什么要拥有这样的通用属性?

The question is, why would you want to have a generic property like this?

当您尝试设置该属性时,您希望它接受什么值?如果答案是什么,也许它的类型应该是 AnyAny?.

What would you expect this property to accept as a value when you're trying to set it? If the answer is anything, maybe its type should be Any or Any?.

这同样适用于读取它 - 您希望从该属性读取的值具有什么类型?如果您根本不想指定类型,那么它可能应该是 AnyAny?.

The same applies for reading it - what type would you expect the value you're reading from this property to have? If you don't want to specify a type at all, again, it should probably be Any or Any?.

实际上在语言中的解决方案,即让类/接口采用类型参数,解决了这些问题.

The solution that's actually in the language, that is having the class/interface take a type parameter, solves these issues.

这篇关于Kotlin 通用属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆