https://kotlinlang.org logo
#getting-started
Title
# getting-started
a

Ayfri

08/08/2021, 2:42 AM
Hi, is it possible to have a default value for a generic type of a class ? Like that code in TypeScript :
Copy code
class Test<T = string> {
    readonly thing: T
}

const a = new Test() // this works
const b = new Test<number>() // this too
n

Nathan Bedell

08/08/2021, 2:59 AM
Hi, unfortunately it looks like this hasn't been implemented yet. I'd love to see something like this feature though!
😕 1
j

James Whitehead

08/08/2021, 4:31 AM
If you are saying
T
can be a subclass of
String
you could do
Copy code
class Test<T : String> {}
d

Dave K

08/08/2021, 4:47 AM
It looks like they’re wanting to omit the <> entirely and have the default implication be that it’s a string, but also support other things explicitly such as Number
Could you not do fun Test() = Test<String>()
blob open mouth 1
with constructor arg or not https://pl.kotl.in/mJLv3yyUg Though with the lateinit var has to have a non nullable value and also isn’t read only. However since the example didn’t have a constructor argument I wasn’t sure what the intended use was
If you’re using a constructor argument then the type may not even be necessary to specify explicitly https://pl.kotl.in/pfl7VDG97
a

Ayfri

08/08/2021, 2:21 PM
This is nice thanks ! Also is there a workaround for interfaces (with also a generic type an some properties that have that type) ?
d

diesieben07

08/08/2021, 2:29 PM
Typealiases can do this:
Copy code
class Test<T> { }
typealias DefaultTest = Test<String>
Not an ideal solution but the closest you can get until we have native support for this in the language.
👍 1
2 Views