Search code examples
kotlinstrong-typing

kotlin get static type of a class property


I'm trying to get the type of some class properties in order to strongly typing my Kotlin Code. In typescript, we can do this (stupid examplebut this is to explain)

class Test {
    private  _prop:string
    constructor(val:Test["_prop"]){
        this._prop = val
    }
     public get prop():Test["_prop"] { return this._prop}
}
const t:Test["_prop"] = "fdds"

The benefit here is that if I need to chnange the type of "_prop", no need to refactor the whole code, as the type is find thanks to Test["_prop"]. Is there a way to do this in Kotlin ?

I've seen reflection functions in Kotlin, but can't get what I want

Kotlin code :

class Test(val prop:Int) {
    fun ppr() {
        println(prop)
    }
    
    fun getProp():Int {
        return prop
    }
}


fun main() {
    println("Hello, world!!!")
    
    
    var t:Test = Test(4)
    t.ppr()
    
    var a:Int = t.getProp()   // how to change :Int by "return type of func Test.prop

}

Solution

  • You can't do it exactly like that in Kotlin, but you can declare a type alias, which sort of achieves the same result - enabling you to change the type of multiple things by editing only one place.

    typealias PropType = Int
    
    class Test(val prop: PropType) {
        fun prop(): PropType {
            return prop
        }
    }
    

    To change the type of both, just change the typealias PropType = Int line.

    However, note that you don't actually need to do this if you just want to write a getter. You don't need to explicitly write getters if all it does is just returning the property's value. If you want to do something extra in the getter, you can do:

    class Test(prop: Int) {
        val prop = prop
            get() {
                // do something extra in the getter
                println("getting prop!")
                return field // return the underlying field
            }
    }
    

    The getter will be called whenever you access Test.prop, and again, you only need to change one place to change the type of the property.