本文是根据慕课网kotlin相关课程本人笔记和个人理解所作
代码部分参考慕课网新kotlin入门课程
这一章主要介绍了泛型的使用,注意逆变和协变的区别
kotlin
fun main() {
val max : String = maxOf<String>("Hello", "World")
//val list = List.Cons(1.0, List.Nil)
val result : Result<String>? = Result.success("Hello")
if(result != null){
println(result.isSuccess)
}
}
fun <T> maxOf(a: T, b: T): T {
TODO()
}
sealed class IntList {
object Nil : IntList(){
override fun toString(): String {
return "Nil"
}
}
data class Cons(val head: Int, val tail: IntList) : IntList(){
override fun toString(): String {
return "$head, $tail"
}
}
fun joinToString(sep: Char = ','): String {
return when(this){
Nil -> "Nil"
is Cons -> "${this.head}$sep${this.tail.joinToString(sep)}"
}
}
}
sealed class List<T> {
object Nil : List<Nothing>(){
override fun toString(): String {
return "Nil"
}
}
data class Cons<E>(val head: E, val tail: List<E>) : List<E>(){
override fun toString(): String {
return "$head, $tail"
}
}
fun joinToString(sep: Char = ','): String {
return when(this){
Nil -> "Nil"
is Cons -> "${this.head}$sep${this.tail.joinToString(sep)}"
}
}
}
java
public class JavaConstraints {
public static <T extends Comparable<T>> T maxOf(T a, T b) {
if (a.compareTo(b) > 0) return a;
else return b;
}
public static <T extends Comparable<T> & Supplier<R>, R extends Number>
R callMax(T a, T b) {
if (a.compareTo(b) > 0) return a.get();
else return b.get();
}
public static void main(String... args) {
}
}
kotlin
fun <T : Comparable<T>> maxOf(a: T, b: T): T {
return if (a > b) a else b
}
fun <T, R> callMax(a: T, b: T): R
where T : Comparable<T>, T : () -> R,
R : Number {
return if (a > b) a() else b()
}
class Map<K, V> where K : Serializable, V : Comparable<V>
fun main() {
val max = maxOf("Hello", "World")
println(max)
}
kotlin
fun main() {
val pair = "Hello" to "World"
val list = List.Cons(1.0, List.Nil)
}
interface Book
interface EduBook : Book
class BookStore<out T : Book> {
fun getBook(): T {
TODO()
}
}
fun covariant(){
val eduBookStore: BookStore<EduBook> = BookStore<EduBook>()
val bookStore: BookStore<Book> = eduBookStore
val book: Book = bookStore.getBook()
val eduBook : EduBook = eduBookStore.getBook()
}
open class Waste
class DryWaste : Waste()
class Dustbin<in T : Waste> {
fun put(t: T) {
TODO()
}
}
fun contravariant(){
val dustbin: Dustbin<Waste> = Dustbin<Waste>()
val dryWasteDustbin: Dustbin<DryWaste> = dustbin
val waste = Waste()
val dryWaste = DryWaste()
dustbin.put(waste)
dustbin.put(dryWaste)
// dryWasteDustbin.put(waste)
dryWasteDustbin.put(dryWaste)
}
sealed class List<out T> {
object Nil : List<Nothing>() {
override fun toString(): String {
return "Nil"
}
}
data class Cons<T>(val head: T, val tail: List<T>) : List<T>() {
override fun toString(): String {
return "$head, $tail"
}
}
fun joinToString(sep: Char = ','): String {
return when (this) {
Nil -> "Nil"
is Cons -> "${this.head}$sep${this.tail.joinToString(sep)}"
}
}
}
operator fun <T> List<T>.get(index: Int): T =
when {
index == 0 && this is List.Cons<T> -> this.head
index > 0 && this is List.Cons<T> -> this.tail[index - 1]
else -> throw IndexOutOfBoundsException()
}
java
public class JavaRawTypes {
public static void main(String... args) {
HashMap<String, Integer> hashMap = getHashMap();
//....
HashMap map = hashMap;
map.put("H", "Hello");
//...
Integer i = hashMap.get("H");
System.out.println(i);
}
public static HashMap<String, Integer> getHashMap(){
return new HashMap<String, Integer>();
}
}
kotlin
fun main() {
//region fold
val queryMap: QueryMap<*, *> = QueryMap<String, Int>()
queryMap.getKey()
queryMap.getValue()
val f: Function<*, *> = Function<Number, Any>()
//f.invoke()
if (f is Function) {
(f as Function<Number, Any>).invoke(1, Any())
}
maxOf(1, 3)
HashMap<String, List<*>>()
//endregion
val hashMap: HashMap<*, *> = HashMap<String, Int>()
//hashMap.get()
}
//region fold
class QueryMap<out K : CharSequence, out V : Any> {
fun getKey(): K = TODO()
fun getValue(): V = TODO()
}
fun <T : Comparable<T>> maxOf(a: T, b: T): T {
return if (a > b) a else b
}
class Function<in P1, in P2> {
fun invoke(p1: P1, p2: P2) = Unit
}
kotlin
inline fun <reified T: AbsModel> modelOf(): ModelDelegate<T> {
return ModelDelegate(T::class)
}
class ModelDelegate<T : AbsModel>(val kClass: KClass<T>) : ReadOnlyProperty<Any, T> {
override fun getValue(thisRef: Any, property: KProperty<*>): T {
return Models.run { kClass.get() }
}
}
object Models {
private val modelMap = ConcurrentHashMap<Class<out AbsModel>, AbsModel>()
fun <T : AbsModel> KClass<T>.get(): T {
return modelMap[this.java] as T
}
fun AbsModel.register() {
modelMap[this.javaClass] = this
}
}
abstract class AbsModel {
init {
Models.run { register() }
}
}
class DatabaseModel : AbsModel() {
fun query(sql: String): Int = 0
}
class NetworkModel : AbsModel() {
fun get(url: String): String = """{"code": 0}"""
}
val x: Int
get() {
return Math.random().toInt()
}
class MainViewModel {
val databaseModel by modelOf<DatabaseModel>()
val networkModel by modelOf<NetworkModel>()
}
fun initModels() {
DatabaseModel()
NetworkModel()
}
fun main() {
initModels()
val mainViewModel = MainViewModel()
mainViewModel.databaseModel.query("select * from mysql.user").let(::println)
mainViewModel.networkModel.get("https://www.imooc.com").let(::println)
}