Kotlin Generic Property

2019-01-20 12:41发布

问题:

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

    }
}

回答1:

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?

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?.

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.



回答2:

No, how should the compiler know what T is? If you don't need the generic type parameter T anyway, you can just declare it as val t: Any.



回答3:

I'm a complete newbie to Kotlin, but a generic property is not really something wrong, is it?

What about this as a showcase. I do understand that this solution does not completely address your question.

interface BaseProperty<T> {
  var value: T
}


class IntProperty(var stringVal: String) : BaseProperty<Int?> {
  override var value: Int?
    get() = Integer.valueOf(stringVal)
    set(v: Int?) {
      stringVal = v.toString()
    }
}

Since the getter and setter of the property are also a functions, it would had been nice if I were able to specify T as generic type. I have tried to use getValue and setValue as generic functions and that seems to work, but not using the Kotlin property idiom.



标签: kotlin