Kotlin Generic Property

后端 未结 4 1136
無奈伤痛
無奈伤痛 2020-12-06 21:45

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

interfac         


        
4条回答
  •  醉酒成梦
    2020-12-06 22:21

    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 {
      var value: T
    }
    
    
    class IntProperty(var stringVal: String) : BaseProperty {
      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.

提交回复
热议问题