I'm unable to get a List of generic type from a custom class (Turns):
val turnsType = TypeToken<List<Turns>>() {}.type val turns = Gson().fromJson(pref.turns, turnsType)
it said:
cannot access '<init>' it is 'public /*package*/' in 'TypeToken'
object: is used in Kotlin to instantiate anonymous class instances which extend from the parent class. In other words, this part object: TypeToken(){} actually creates an anonymous class that is a child of TypeToken class.
protected TypeToken() Constructs a new type literal. Derives represented class from type parameter. Clients create an empty anonymous subclass.
Gson is a Java/Kotlin library for converting Java/Kotlin Objects into JSON representation, also a JSON string to an equivalent Java/Kotlin object. We have some ways to add Gson library to our Kotlin project.
Create this inline fun:
inline fun <reified T> Gson.fromJson(json: String) = fromJson<T>(json, object: TypeToken<T>() {}.type)
and then you can call it in this way:
val turns = Gson().fromJson<Turns>(pref.turns) // or val turns: Turns = Gson().fromJson(pref.turns)
Previous Alternatives:
ALTERNATIVE 1:
val turnsType = object : TypeToken<List<Turns>>() {}.type val turns = Gson().fromJson<List<Turns>>(pref.turns, turnsType)
You have to put object :
and the specific type in fromJson<List<Turns>>
ALTERNATIVE 2:
As @cypressious mention it can be achieved also in this way:
inline fun <reified T> genericType() = object: TypeToken<T>() {}.type
use as:
val turnsType = genericType<List<Turns>>()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With