Kotlin通用财产 [英] Kotlin Generic Property

查看:84
本文介绍了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.

这很可能是因为您必须在 some 点声明属性的类型.泛型函数很有意义,因为您可以使用具有某种静态类型的参数来调用它们(或者对于扩展函数,可以在此类参数上称为 on ).

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天全站免登陆