阅读笔记第四章

115 阅读3分钟

[TOC]

本章节有些扩展类的代码没有贴,懒惰了。。。

枚举与扩展

枚举类

枚举类的基本用法

  • kotlin 中的一切都是对象 枚举类里面的属性都是对象
enum class Direction{
    NORTH,SOUTH,WEST,EAST
}

/ / 定义一个枚举类变量
var directionl: Direction·
/ / 定义一个枚举类变量,并初始化
var direction2: Direction = Direction .NORTH / / //未指定数据类型,通过右侧的赋值自动检测类型

java 与 cotlin枚举类定义


//java 代码

public class EnumTest{
    enum Direction{
        NORTH(1) , SOUTH(2),EAST(3),WEST(4);
        
        private int mValue;
        
        private Dirction(int value){
            mValue = value;
        }
        
        @override
        public String toString(){
            return String.ValueOf(mValue);
        }
    }
}

public void main(String[] args){
    Direction direction = new Direction.NORTH();
    System.out.println(direction);
}





//kotlin 代码


enum class Direction private constructor (val d: Int){
    // 通过 Direction 的构造器传入枚举值对应的值
       NORTH(l), SOUTH(2), WEST(3), EAST(4);
       override fun toString():String{
           return d.toString()
       }
       
}


fun main(args:Array<String>){
    var dir1:Direction = Direction.NORTH
    var dir2 = Direction.NORTH
    println(dir1)
    println(dir2)
}

扩展

扩展原生API

扩展是kotlin非常重要的功能,通过扩展,可以在没有源码的情况下向类中添加成员,也可以砸团队开发的情况下,通过扩展,将功能模块分发给多个开发人员。

 // 为 MutableList 类添加一个 swap 方法,用于交互任意两个集合元素的位置
 fun MutableList<Int>.swap(index1:Int,index2:Int){
     val temp = this[index1]
     this[index1] = this[index2]
     this[index2] = temp
 }
 val  mutableList = mutableListOf(1,2,3)
 mutableList.swap(1,2)
 println(mutableList)
 
 
 //ArrayList添加一个 swap 方法
 
 fun  ArrayList<Int>.swap(index1:Int,index2:Int){
     val temp = this[index1]
     this[index1] = this[index2]
     this[index2] = temp
 }
 

扩展自定义类

open class Parent(val valuel:Int, val value2:Int) {
var mValuel: Int = valuel 
var mValue2: Int = value2 
fun add ():工nt{
    return mValuel + mValue2
}

class Child(valuel:Int, value2:Int): Parent (valuel, value2) {
fun sub(): Int{
    return mValuel - mValue2
}

// 通过扩展向 Parent 类添加一个 printResult 方法 
fun Parent.printResult(){
    println (”${mValuel} + ${mValue2} =♀{ add()}”)
}
 / / 通过扩展向 Child 类添加一个 printResult 方法
fun Child.printResult (){
    println (”♀{mValuel} - ${mValue2} = ${sub ()}”)
}

fun main(args:Array<String>){
    var parentl: Parent = Parent(l, 2)
    var parent2: Parent = Child (l,2) parentl.printResult{) // 输出 1 + 2 = 3 parent2.printResult() // 输出 1 + 2 = 3
}

成员函数冲突的解决方案

很明显,如果类内部的成员函数和通过扩展添加的成员函数冲 突,那么内部成员函数的优 先级更高,因此,通过扩展无法覆盖内部成员函数 。

扩展属性

扩展属性需要实现setter部分

var MyClass.value:Int
    get() = mValue
    set(value){
        field = value
    }

注意: 由于扩展属性没有 backingfield字段,因此保存和获取属性值,需要使用一个类成员变量。 但成员变量需要声明为 public,否则扩展属性无法访问。

扩展伴随对象( Companion Object )

如果类中有伴随对象,那么可以利用扩展为伴随对象添加成员。 由于 KotIin类不支持静态成员,因此引入了伴随对象(CompanionObject)来解决类没有静态成员所带来的尴尬。

class MyClass{
    Companion object{
        
    }
}

fun MyClass.Companion.test(){
    println("这是伴随对象成员函数")
}

fun  main(args:Array<String>){
    MyClass().test()
}


扩展的范围

调用特定类的成员函数

扩展成员的继承

尽管枚举类并不是在代码中总出现,但用来定义可枚举的一组相关值还是非常好的, 至少 让代码变得更可读(远比使用常量或直接使用数字要好)。而扩展在很多语 言 中都支持, 如 Apple 公司推出的 Swift语言,也支持扩展 。 Kotlin 这种 Google 强力推荐的语言自然也会支持 扩展。充分利用 Kotlin 扩展,可以让代码变得更容易维护,同时也带来了更大的灵活性 。