Kotlin 基本语法5 继承,接口,枚举,密封

1.继承与重写的Open关键字

Kotlin 复制代码
open class Product(
    val name:String
) {

    fun description() = "Product: $name"

   open fun load() = "Nothing .."


}


class LuxuryProduct:Product("Luxury"){//继承需要调用 父类的主构造函数

    override fun load(): String {
        return "LuxuryProduct loading ..."
    }

}

fun main() {
    val p:Product = LuxuryProduct()
    println(p.load())
}

2.类型检测

3.智能类型转化

Kotlin 复制代码
import java.io.File

open class Product(
    val name:String
) {

    fun description() = "Product: $name"

   open fun load() = "Nothing .."


}


class LuxuryProduct:Product("Luxury"){//继承需要调用 父类的主构造函数

    override fun load(): String {
        return "LuxuryProduct loading ..."
    }
    fun  special():String = "Speical LuxuryProduct Function"

}

fun main() {
    val p:Product = LuxuryProduct()
    println(p.load())

    println(p is Product)
    println(p is LuxuryProduct)
    println(p is File)


    if (p is LuxuryProduct){
        p.special()
    }
}

4. Any 超类

跨平台支持得更好,他的Any类里的 toString hashcode equals 在不同平台有不同的实现,是为了更好的跨平台支持。

5. 对象

5.1 object关键字 单例模式

Kotlin 复制代码
object ApplicationConfig{
    var name :String = "singleName"
    init {
        println("ApplicationConfig loading ...")
    }
    fun doSomething(){
        println("doSomething")
    }


}

fun main() {
    //类名,实例名 就是一个单例对象
    ApplicationConfig.doSomething()
    println(ApplicationConfig)
    println(ApplicationConfig)
    println(ApplicationConfig)
    println(ApplicationConfig===ApplicationConfig)
}

5.2 对象表达式 相当于匿名内部类

Kotlin 复制代码
open class Player{
    open fun load() = "loading nothing"
}

fun main() {
    val p = object : Player(){ //匿名内部类相当于
        override fun load(): String {
            return "anonymous nothing"
        }
    }
    println(p.load())
}

5.3 伴生对象 一个类只能有一个

Kotlin 复制代码
import java.io.File

open class ConfigMap(val name:String){

    companion object{ //伴生对象  相当于静态内部类 创建的单例对象
        // 不管这个ConfigMap类实例化多少次,这个伴生对象就是单例,因为是不基于对象创建的,是类加载时创建的
        private const val PATH = "XXXX"

        var s:String ="asd"
        fun load() = File(PATH).readBytes()

    }

}

fun main() {
    ConfigMap.load()
}
Kotlin 复制代码
import java.io.File

open class ConfigMap(val name:String){

    companion object{ //伴生对象  相当于静态内部类 创建的单例对象
        // 不管这个ConfigMap类实例化多少次,这个伴生对象就是单例,因为是不基于对象创建的,是类加载时创建的
        private const val PATH = "XXXX"

        var s:String ="asd"
        fun load() = File(PATH).readBytes()
        init {
            println("companion object 被加载了")
        }

    }

}

fun main() {
    ConfigMap("a")
}

6. 嵌套类 实际上就是 静态内部类

Kotlin 复制代码
class Player2 {
     class Equipment(var name: String) {
        fun show() = println("equipment:$name")
    }

    fun battle(){

    }


}


fun main() {
    val equipment = Player2.Equipment("sharp knife")


}

7. 数据类

Kotlin 复制代码
data class Coordinate(var x: Int, var y: Int) {
    var isInBounds = x > 0 && y > 0

}

fun main() {
    println(Coordinate(10, 20))
    //== 比较的是内容,equals,Any 默认实现 === ,比较引用
    //=== 比较引用


    println(Coordinate(10, 20) == Coordinate(10, 20))
}

8.copy函数 数据类专属

Kotlin 复制代码
data class Student (var name:String,val age:Int){
    private val hobby = "music"
    var subject:String

    init {
        println("initializing student")
        subject = "math"
    }
    constructor(_name:String):this(_name,10)

    override fun toString(): String {
        return "Student(name='$name', age=$age, hobby='$hobby', subject='$subject')"
    }
    constructor(_name:String,_age:Int,_hobby:String,_subject:String):this(_name,10){
        subject=_subject
    }


}

fun main() {
    val s = Student("JACK")

    val copy = s.copy(name = "Rose") //copy只跟主构造函数有关

    println(s)
    println(copy)
}

9.结构声明

Kotlin 复制代码
class PlayerScore(var experience:Int ,val level :Int,val name:String){
    operator fun component1() = experience  //component后面那个数字必须从1开始
    operator fun component2() = name


}

fun main() {
    /**
     * 普通的结构
     */
   val (x,y) = PlayerScore(10,20,"小智")
    println("$x $y")




}
Kotlin 复制代码
data class PlayerScore(var experience:Int ,val level :Int,val name:String){
    
}

fun main() {
    /**
     * 数据类自带的结构
     */
   val (x,y) = PlayerScore(10,20,"小智")
    println("$x $y")
}

10. 运算符重载

Kotlin 复制代码
 data class Coordinate(var x: Int, var y: Int) {
    var isInBounds = x > 0 && y > 0

//    operator fun plus(other:Coordinate):Coordinate {
//        return Coordinate(x+other.x,y+other.y)
//    }
    
    operator  fun  plus(other: Coordinate) = Coordinate(x+other.x,y+other.y)

}

fun main() {

    val c1 = Coordinate(10, 20)
    val c2 = Coordinate(10, 20)

    println(c1+c2)
}

11.枚举类

Kotlin 复制代码
enum class Direction {
    EAST,
    WEST,
    SOUTH,
    NORTH
}

fun main() {
    println(Direction.EAST)
    println(Direction.EAST is Direction)
}

11.1 枚举类定义函数

Kotlin 复制代码
enum class Direction (private val coordinate: Coordinate){
    EAST(Coordinate(1,0)),
    WEST(Coordinate(-1,0)),
    SOUTH(Coordinate(0,-1)),
    NORTH(Coordinate(0,1));


    fun updateCoordinate(playerCoordinate: Direction) =
        Coordinate(playerCoordinate.coordinate.x+coordinate.x,
            playerCoordinate.coordinate.y+coordinate.y)

}

fun main() {
    val updateCoordinate = Direction.EAST.updateCoordinate(Direction.WEST)
    println(updateCoordinate)
}

11.2 代数数据类型

Kotlin 复制代码
enum class LicenseStatus {
    UNQUALIFIED,
    LEARNING,
    QUALIFIED;

}

class Driver(var status: LicenseStatus) {
    fun checkLicense(): String {
        return when (status) {
            LicenseStatus.UNQUALIFIED -> "没资格"
            LicenseStatus.LEARNING -> "在学"
            LicenseStatus.QUALIFIED -> "有资格"
        }
    }

}

fun main() {
    println(Driver(LicenseStatus.LEARNING).checkLicense())
}

12.密封类

Kotlin 复制代码
//密封
sealed class LicenseStatus2 {
    object UnQualified : LicenseStatus2(){
        val id :String = "2131"
    }
    object Learning : LicenseStatus2()
    class Qualified(val licenseId: String) : LicenseStatus2()

}

class Driver2(var status: LicenseStatus2) {
    fun checkLicense(): String {
        return when (status) {
            is LicenseStatus2.UnQualified -> "没资格 ${(this.status as LicenseStatus2.UnQualified).id}"
            is LicenseStatus2.Learning -> "在学"
            is LicenseStatus2.Qualified -> "有资格,驾驶证编号 ${(this.status as LicenseStatus2.Qualified).licenseId}"
        }
    }

}



fun main() {
    println(Driver2(LicenseStatus2.UnQualified).checkLicense())
}
相关推荐
番茄啊2 小时前
linux 开启xftp连接
linux·运维·服务器
OpsEye3 小时前
大模型 Token 计量不准,是什么原因,怎么解决??
javascript·ai编程
Julien20043 小时前
管理机密(一)
运维·服务器·开发语言·学习方法
独隅4 小时前
WebStorm Windows 版 React / Next.js 实战替换指南
javascript·windows·webstorm
冷眸_4 小时前
同名食材不能直接相减:一个 JavaScript 用量模型的边界
javascript
灿飞4 小时前
Kotlin与Java虚拟机七:空安全:把十亿美元的错误消灭在类型系统里
java·kotlin
apollo_qwe4 小时前
接口超时了,前端为什么不能直接重试?
javascript·http
AOI小白新手上路8 小时前
深度学习算力购置方案分析:本地 RTX 4090 服务器 vs 云端租赁
服务器·人工智能·深度学习
千桐科技8 小时前
qKnow智能体构建平台专业版 v3.1.5 发布:扩容工作流编排调用能力,上线Text2SQL插件,拓宽数据类智能应用构建边界
服务器·数据库·oracle·qknow
雪落漂泊8 小时前
Linux进程(四)概念:命令行参数和环境变量篇
linux·运维·服务器