4

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.

0

1 Answer 1

3

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>
Sign up to request clarification or add additional context in comments.

1 Comment

thanks, I see your point about violating definition. sad part is that I have to rewrite old Java code in Kotlin and still keep them compatible. otherwise I'd go with your solution. still, 2 functions is better than 4 overloaded we had..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.