I have a function that returns generic type based on passed parameter, but I can't set its default value. Here's example function I have:
fun <T : BaseClass> parse(json: String, gson: Class<T> = BaseClass::class): T =
Gson().fromJson(json, gson)
However, I get type mismatch error for default parameter: expected Class<T>
, found Class<BaseClass>
.
I can achieve same thing using second function:
fun <T : BaseClass> parse(json: String, gson: Class<T>): T =
Gson().fromJson(json, gson)
fun BaseClass parse(json: String) =
parse(json, BaseClass::class)
Which doesn't look Kotlin-way. Is it possible to have default generic parameter? Thanks.
Your first line of code wouldn't be usable in practice. What happens if you do this?
It would be violating its own definition of the generic type.
Your solution above may be the best you can do for your use case. You might also consider using a reified type like this:
This doesn't provide you any default, but it allows the compiler to infer the type where possible, so in some cases you wouldn't have to specify the class: