On the generics of kotlin

import kotlin.reflect.KProperty
import kotlinx.serialization.*
import kotlinx.serialization.json.JSON.Companion.stringify
class Delegate<T: Any>(val key: String, private val default: T) {
  operator fun getValue(thisRef: Any?, property: KProperty<*>): String {
    return "$thisRef, thank you for delegating "${property.name}" to me!"
  }

  operator fun setValue(thisRef: Any?, property: KProperty<*>, value: String) {
    println("$value has been assigned to "${property.name}" in $thisRef.")
    stringify(default)
  }
}
fun main(args: Array<String>) {
  var t by Delegate("test", Data("t"))
}
@Serializable
data class Data(val name: String)


the generics of the Delegate class are constrained to the word classes under Any, so why doesn"t stringify accept

?
May.02,2021

import kotlin.reflect.KProperty
import kotlinx.serialization.*
import kotlinx.serialization.json.JSON.Companion.stringify

class Delegate(val key: String, private val default: Data) {

//    init {
//        println(stringify(default))
//    }

    operator fun getValue(thisRef: Any?, property: KProperty<*>): String {
        return "$thisRef, thank you for delegating '${property.name}' to me!"
    }

    operator fun setValue(thisRef: Any?, property: KProperty<*>, value: String) {
        println("$value has been assigned to '${property.name}' in $thisRef.")
        stringify(default)
    }
}

fun main(args: Array<String>) {
    var t by Delegate("test", Data("t"))

}

@Serializable
data class Data(val name: String)

No problem without generics. Generics should not be used here. Serialization should tell it the exact type at compile time

< hr >

https://github.com/JetBrains/.
reified needs a definite type

Menu