不会真的学不会kotlin吧?(五)类型进阶

本文是根据慕课网kotlin相关课程本人笔记和个人理解所作
代码部分参考慕课网新kotlin入门课程

文章目录

    • 本章简介
    • 结构导图
    • 类的构造器
    • 成员可见性
    • 类属性的初始化
    • 代理 Delegates
    • 单例
    • data class数据类
    • 内部类
    • 枚举类
    • 密封类
    • 内联类
    • EG

本章简介

这一章主要就是要注意java类和kotlin类的区别一些的,看看知道怎么用就可以了

结构导图

不会真的学不会kotlin吧?(五)类型进阶_第1张图片

类的构造器

java

public class Person {
    private int age;
    private String name;

    public Person(int age, String name) {
        this.age = age;
        this.name = name;
    }

    {
        System.out.println("1");
    }

    {
        System.out.println("2");
    }

}

kotlin

abstract class Animal
class Person(var age: Int, var name: String = "unknown") {
    override fun equals(other: Any?) = (other as? Person)?.name?.equals(name) ?: false
    override fun hashCode() = name.hashCode()
}

val persons = HashMap<String, Person>()
fun Person(name: String): Person {
    return persons[name]
        ?: Person(1, name).also { persons[name] = it }
}

成员可见性

可见性类型 Java Kotlin
public 公开 与Java相同,默认
internal X 模块内可见
default 包内可见,默认 X
protected 包内及子类可见 类内及子类可见
private 类内可见 类或文件内可见
可见性类型 顶级声明 成员
public V V V
internal V,模块 V,模块 V,模块
protected X X V
private V,文件 V,文件 V,类

类属性的初始化

方案名称 推荐指数 理由
可空类型 1 增加代码复杂度﹔初始化与声明分离; 调用处需要做判空处理
lateinit 2 初始化与声明分离;调用处虽无需判空 处理,但潜在的初始化问题可能被掩盖
lazy 3 初始化与声明内聚;无需声明可空类型

代理 Delegates

kotlin

//region api
interface Api {
    fun a()
    fun b()
    fun c()
}

class ApiImpl : Api {
    override fun a() {}
    override fun b() {}
    override fun c() {}
}

class ApiWrapper(val api: Api) : Api by api {
    override fun c() {
        println("c is called.")
        api.c()
    }
}
//endregion

class SuperArray<E>(
    private val list: MutableList<E?> = ArrayList(),
    private val map: MutableMap<Any, E> = HashMap()
) : MutableList<E?> by list, MutableMap<Any, E> by map {

    override fun isEmpty() = list.isEmpty() && map.isEmpty()

    override val size: Int
        get() = list.size + map.size

    override fun clear() {
        list.clear()
        map.clear()
    }

    override operator fun set(index: Int, element: E?): E? {
        if (list.size <= index) {
            repeat(index - list.size + 1) {
                list.add(null)
            }
        }
        return list.set(index, element)
    }

    override fun toString(): String {
        return """List: [$list]; Map: [$map]"""
    }
}

fun main() {
    val superArray = SuperArray<String>()
    val superArray2 = SuperArray<String>()
    superArray += "Hello"
    superArray["Hello"] = "World"
    superArray2[superArray] = "World"

    superArray[1] = "world"
    superArray[4] = "!!!"

    println(superArray)
    println(superArray2)
}

kotlin

class Person(val name: String){
    val firstName by lazy {
        name.split(" ")[0]
    }
    val lastName by lazy {
        name.split(" ")[1]
    }
}

class StateManager {
    var state: Int by Delegates.observable(0) {
        property, oldValue, newValue ->
        println("State changed from $oldValue -> $newValue")
    }
}


class Foo {
    val x: Int by X()

    var y: Int by X()
}

class X {
    operator fun getValue(thisRef: Any?, property: KProperty<*>): Int {
        return 2
    }

    operator fun setValue(thisRef: Any?, property: KProperty<*>, i: Int) {

    }
}

fun main() {
    val stateManager = StateManager()
    stateManager.state = 3
    stateManager.state = 4

    println(Foo().x)
}

单例

java

public class Singleton {
    public static final Singleton INSTANCE = new Singleton();

}

kotlin

object Singleton: Runnable{
    override fun run() {

    }

    @JvmField var x: Int = 2
    @JvmStatic fun y(){ }

    init {

    }
}

class Foo {
    companion object {
        @JvmField var x: Int = 2
        @JvmStatic fun y(){  }
    }
}

fun main() {
    Singleton.x
    Singleton.y()

    val foo = Foo()
}

data class数据类

JavaBean dataclass
构造方法 默认无参构造 属性作为参数
字段 字段私有,Getter/Setter公开 属性
继承性 可继承也可被继承 不可被继承
component 相等性、解构等

java

public class Book {
    private long id;
    private String name;
    private Person person;

    public long getId() {
        return id;
    }

    public Book id(long id) {
        this.id = id;
        return this;
    }

    public String getName() {
        return name;
    }

    public Book name(String name) {
        this.name = name;
        return this;
    }

    public Person getPerson() {
        return person;
    }

    public Book person(Person person) {
        this.person = person;
        return this;
    }
}

kotlin

@PoKo
data class Book(val id: Long,
                val name: String,
                val author: Person) {

}

data class Person(val id: Long, val name: String, val age: Int)

fun main() {
//    val book = Book(0, "Kotlin in Action", Person(1, "Dmitry", 40))
//    book.copy()
    val id = book.component1()
    val name = book.component2()
    val author = book.component3()
//
//    val (id, name, author) = book
//
//    val pair = "Hello" to "World"
//    val (hello, world) = pair

    val book = Book::class.java.newInstance()

}

内部类

java

public class Outer {
    class Inner { }
    static class StaticInner { }
}

kotlin

class Outer {
    inner class Inner
    class StaticInner
}

object OuterObject {
    object StaticInnerObject
}

fun main() {
    val inner = Outer().Inner()
    val staticInner = Outer.StaticInner()
}

枚举类

java

public class JavaEnums {
    enum State
            implements Runnable {
        Idle {
            @Override
            public void run() {

            }
        }, Busy {
            @Override
            public void run() {

            }
        };
    }





    public static void main(String... args) {
        System.out.println(State.Idle.getClass().getSuperclass().getSuperclass());

        System.out.println(State.Idle.name()); // Idle
        System.out.println(State.Idle.ordinal()); // 0
    }
}

kotlin

enum class State: Runnable{
    Idle, Busy{
        override fun run() {
            println("For Busy State.")
        }
    };

    override fun run() {
        println("For  Every State.")
    }
}

//region fold
fun State.successor(): State? {
    return State.values().let {
        if (ordinal + 1 >= it.size) null
        else it[ordinal + 1]
    }
}

fun State.predecessor(): State? {
    return State.values().let {
        if (ordinal - 1 < 0) null
        else it[ordinal - 1]
    }
}

enum class Color {
    White, Red, Green, Blue, Yellow, Black
}
//endregion

fun main() {
    State.Idle.run()
    State.Busy.run()

    println(State.Idle.successor())
    println(State.Busy.successor())

    State.Idle.name // Idle
    State.Idle.ordinal // 0

    val state = State.Idle
    val value = when (state) {
        State.Idle -> { 0 }
        State.Busy -> { 1 }
    }

    if(state <= State.Idle){

    }


    val colorRange = Color.White .. Color.Green
    val color = Color.Blue
    println(color in colorRange)
}

密封类

kotlin

//region entity
data class Song(val name: String, val url: String, var position: Int)

data class ErrorInfo(val code: Int, val message: String)

object Songs {
    val StarSky = Song("Star Sky", "https://fakeurl.com/321144.mp3", 0)
}
//endregion

//region state
sealed class PlayerState

object Idle : PlayerState()

class Playing(val song: Song) : PlayerState() {
    fun start() {}
    fun stop() {}
}

class Error(val errorInfo: ErrorInfo) : PlayerState() {
    fun recover() {}
}
//endregion

class Player {
    var state: PlayerState = Idle

    fun play(song: Song) {
        this.state = when (val state = this.state) {
            Idle -> {
                Playing(song).also(Playing::start)
            }
            is Playing -> {
                state.stop()
                Playing(song).also(Playing::start)
            }
            is Error -> {
                state.recover()
                Playing(song).also(Playing::start)
            }
        }
    }
}

fun main() {
    val player = Player()
    player.play(Songs.StarSky)
}

内联类

kotlin

inline class BoxInt(val value: Int): Comparable<Int> {
    override fun compareTo(other: Int)
            = value.compareTo(other)

    operator fun inc(): BoxInt {
        return BoxInt(value + 1)
    }
}

inline class State(val ordinal: Int) {
    companion object {
        val Idle = State(0)
        val Busy = State(1)
    }

    fun values() = arrayOf(Idle, Busy)

    val name: String
        get() = when (this) {
            State.Idle -> "Idle"
            State.Busy -> "Busy"
            else -> throw  IllegalArgumentException()
        }
}

inline class Color(val value: UInt) {
    companion object {
        val Red = Color(0xFFFF0000u)
        val Green = Color(0xFF00FF00u)
        val Blue = Color(0xFF0000FFu)
    }

    fun values() = arrayOf(Red, Green, Blue)

    val name: String
        get() = when (this) {
            Red -> "Red"
            Green -> "Green"
            Blue -> "Blue"
            else -> throw  IllegalArgumentException()
        }
}

fun main() {
    var boxInt = BoxInt(5)
    if(boxInt < 10){
        println("value is less than 10")
    }

    val newValue = boxInt.value * 200
    println(newValue)
    boxInt++
    println(boxInt)
    
    //优化
    var value = 5
    val newValue = value * 200
    
    BoxInt.inc-imlp(value)
    printLn(BoxInt(value))
    
}

EG

kotlin

class PropertiesDelegate(private val path: String, private val defaultValue: String = ""){

    private lateinit var url: URL

    private val properties: Properties by lazy {
        val prop = Properties()
        url = try {
            javaClass.getResourceAsStream(path).use {
                prop.load(it)
            }
            javaClass.getResource(path)
        } catch (e: Exception) {
            try {
                ClassLoader.getSystemClassLoader().getResourceAsStream(path).use {
                    prop.load(it)
                }
                ClassLoader.getSystemClassLoader().getResource(path)!!
            } catch (e: Exception) {
                FileInputStream(path).use {
                    prop.load(it)
                }
                URL("file://${File(path).canonicalPath}")
            }
        }

        prop
    }

    operator fun getValue(thisRef: Any?, property: KProperty<*>): String {
        return properties.getProperty(property.name, defaultValue)
    }

    operator fun setValue(thisRef: Any?, property: KProperty<*>, value: String) {
        properties.setProperty(property.name, value)
        File(url.toURI()).outputStream().use {
            properties.store(it, "Hello!!")
        }
    }
}

abstract class AbsProperties(path: String){
    protected val prop = PropertiesDelegate(path)
}

class Config: AbsProperties("Config.properties"){
    var author by prop
    var version by prop
    var desc by prop
}

fun main() {
    val config = Config()
    println(config.author)
    config.author = "Bennyhuo"
    println(config.author)
}
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 -> {
                "${head}$sep${tail.joinToString(sep)}"
            }
        }
    }
}

fun IntList.sum(): Int {
    return when(this){
        IntList.Nil -> 0
        is IntList.Cons -> head + tail.sum()
    }
}

operator fun IntList.component1(): Int? {
    return when(this){
        IntList.Nil -> null
        is IntList.Cons -> head
    }
}

operator fun IntList.component2(): Int? {
    return when(this){
        IntList.Nil -> null
        is IntList.Cons -> tail.component1()
    }
}

operator fun IntList.component3(): Int? {
    return when(this){
        IntList.Nil -> null
        is IntList.Cons -> tail.component2()
    }
}

fun intListOf(vararg ints: Int): IntList {
    return when(ints.size){
        0 -> IntList.Nil
        else -> {
            IntList.Cons(
                ints[0],
                intListOf(*(ints.slice(1 until ints.size).toIntArray()))
            )
        }
    }
}

// [0, 1, 2, 3]
fun main() {
    //val list = IntList.Cons(0, IntList.Cons(1,  IntList.Cons(2,  IntList.Cons(3, IntList.Nil))))
    val list = intListOf(0, 1, 2, 3)
    println(list)
    println(list.joinToString('-'))
    println(list.sum())

    val (first, second, third) = list

    println(first)
    println(second)
    println(third)

    //val (a, b, c, d, e) = listOf()
}

你可能感兴趣的:(不会真的学不会kotlin把?)