Skip to content

Instantly share code, notes, and snippets.

@wcang
Created December 28, 2019 01:17
Show Gist options
  • Save wcang/9cf436d1bc948de691ea23ff4b2f66a2 to your computer and use it in GitHub Desktop.
Save wcang/9cf436d1bc948de691ea23ff4b2f66a2 to your computer and use it in GitHub Desktop.
open class Something<WTF>(val wtf: WTF)
{
init {
println("init something")
}
}
interface Blargh<T> {
fun getArg(): T
}
class StringThing(wtf: String) : Something<String>(wtf), Blargh<String> {
override fun getArg(): String {
return wtf
}
}
interface Creator<out T> {
fun create(): T
}
data class Person(val firstName: String, val lastName: String) {
fun reproduce(): Person {
return Person("John", lastName)
}
}
class RealKereta<T : Person>(val owner: T): Creator<T> {
override fun create(): T {
return owner.reproduce() as T
}
}
interface Another {
companion object {
fun wtf() {
println("what a terrible failure")
}
}
}
/*
Create new instances of the class specified as a type parameter
Can work with some trickeries
*/
inline fun <reified T: Creator<T>> createInstance(value: T): T {
return value.create()
}
/*
Use a non-reified type parameter as a type argument when calling a function
with a reified type parameter
Can't work. It makes sense because compiler can't inline and substitute the type directly
fun <T: Creator<T>> nonreified(value: T) : T {
return createInstance(value)
}
*/
/*
Call methods on the companion object of the type parameter class, can't work
inline fun <reified T: Another> createInstance(): T {
return T.wtf()
}*/
fun main(args: Array<String>) {
args.forEach(::println)
val something = Something("merry xmas")
println(something.wtf)
val string = StringThing("it's me again")
println(string.getArg())
Another.wtf()
println(RealKereta(Person("James", "Doe")).create())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment