1

How to create a generic interface with a nested data class that uses this generic type in Kotlin?

Something like this:

interface Exemplary<T> {

    data class Result(val value: T)

    ...
}

2 Answers 2

2

Also data class should be generic:

interface Exemplary<T> {

    data class Result<T>(val value: T)

    fun getResult(): Result<T>
}
Sign up to request clarification or add additional context in comments.

Comments

0

There's no e.g. Exemplary<Int>.Result but just Exemplary.Result; there's no T to be found without making Result generic as in Lukas' answer.

But there is an alternative: inner classes. If you want T to be fixed by the interface instance, e.g.

val x: Exemplary<Int> = ...
val y = new x.Result(3)

you need to make the class inner, but then it can't be data and you'll need to implement the methods yourself.

Comments

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.