Reputation: 371
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.
Upvotes: 4
Views: 6241
Reputation: 93541
Your first line of code wouldn't be usable in practice. What happens if you do this?
class Derived: BaseClass()
val x = parse<Derived>(someJson)
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:
inline fun <reified T : BaseClass> parse(json: String): T =
Gson().fromJson(json, T::class)
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:
fun someFunction(derived: Derived) {
//...
}
someFunction(parse(someJson)) // no need to specify <Derived>
Upvotes: 3