kotlin学习 - Kotlin 真泛型

kotlin学习 - Kotlin 真泛型

  • Gson封装
1
2
3
4
5
6
7
8
9
10
11
/**
* 为 Gson 增加一个扩展方法
* 由于是 真泛型,因此必须是内联函数
*/
inline fun <reified T> Gson.fromJson(json: String): T {
/**
* 注意这里,可以直接获取 对应 T 的字节码
*/
return fromJson(json, T::class.java)
}

  • MVP 封装
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

class View<T>(val clazz: Class<T>) {
val presenter by lazy { clazz.newInstance() }

//伴生对象会在类放入类加载器中时执行。在类构造方法执行前。
companion object {
//重载构造函数
inline operator fun <reified T> invoke() = View(T::class.java)
}
}

class Presenter {
override fun toString(): String {
return "presenter"
}
}

fun main(args: Array<String>) {
val a = View.invoke<Presenter>().presenter
println(a)
val b = View<Presenter>().presenter
println(b)
}