Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin Generic Property

Tags:

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

    }
}
like image 980
Jefferson Tavares Avatar asked May 20 '17 19:05

Jefferson Tavares


People also ask

What is a generic type in Kotlin?

Generics are the powerful features that allow us to define classes, methods and properties which are accessible using different data types while keeping a check of the compile-time type safety. Creating parameterized classes – A generic type is a class or method that is parameterized over types.

How do you declare a generic variable in Kotlin?

We can make generic variable using this kind of syntax: "val destinationActivity: Class<*>".


2 Answers

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.

like image 167
zsmb13 Avatar answered Oct 05 '22 23:10

zsmb13


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.

like image 41
Rudolf Avatar answered Oct 06 '22 00:10

Rudolf