默认参数和扩展函数(一)

xiaoxiao2021-02-28  122

//函数默认参数 fun divide(divisor:BigDecimal, scale: Int = 0,roundingMode: RoundingMode = RoundingMode.UNNECESSARY):Unit{ } //调用divide函数 的几种方式 fun testDefaultParmas(){ divide(BigDecimal(12.34)) divide(BigDecimal(12.34),8) divide(BigDecimal(12.34),8,RoundingMode.HALF_DOWN) //divide(BigDecimal(12.34),RoundingMode.HALF_DOWN)这种方式是错误的 参数顺序不能混乱 除非 命名参数 divide(BigDecimal(12.34),roundingMode = RoundingMode.HALF_DOWN)//命名参数 可以混乱参数调用顺序 } //默认参数 也可以应用在构造函数中 class Student(val name:String ,val registered:Boolean, credits:Int){ constructor(name:String):this(name,false,0) constructor(name:String, registered: Boolean):this(name,false,0) } //上面代码构造函数可以直接写成下面这种形式 class Student2(val name: String, val registered: Boolean = false, credits: Int= 0){ } //扩展某个类增添一个函数 将list 中第k 到size的元素复制出来 abstract class DroppableList<E> : ArrayList<E>(){ fun drop(k: Int): List<E>{ val resultSize = size - k when{ resultSize <= 0 -> return emptyList<E>() else -> { val list = ArrayList<E>(resultSize) for(index in k..size-1){ list.add(this[index]) } return list } } } } //如果想扩展的类 被final修饰 没办法继承 可以通过传递这个类的实例 写一个工具类去拓展它 fun <E> drop(k: Int, list: List<E>): List<E>{ val resultSize = list.size -k when{ resultSize <= 0 -> return emptyList() else ->{ val newList = ArrayList<E>(resultSize) for(index in k .. list.size-1){ newList.add(list[index]) } return newList } } } //或者写成继承函数的形式 这个函数可以写在一个包中 调用时候引入包名 fun<E> List<E>.drop(k: Int):List<E>{ val resultSize = size -k when{ resultSize <= 0 -> return emptyList() else ->{ val newList = ArrayList<E>(resultSize) for(index in k .. size-1){ newList.add(this[index]) } return newList } } } //调用继承函数 drop的测试类 fun testExtendFun(){ val list = listOf(1,2,3) val dropedList = list.drop(2) //此时drop函数 在同一个文件中 所以可以直接调用 } //继承函数注意: 不能扩展已有的函数,如果函数名 和原来类中的函数名 相同 而且参数相同 将不会被调用 因为编译器找函数调用的时候 优先找成员函数,找不到才会找继承函数 //null 也可以有继承函数 fun Any?.safeEquals(other: Any?): Boolean{ if(this == null && other == null) return true if(this == null) return false return this.equals(other) } //扩展函数 extension function 我几把的叫错了 叫成了继承函数 改口 //扩展函数 不光能写在最外层 作为类似静态函数使用 也可以写在类里面 作为成员函数使用 class Mappings{ private val map = hashMapOf<Int,String>() private fun String.stringAdd():Unit{ map.put(hashCode(),this)//此时hashcode 方法 在String 的扩展函数里面 调用的是String的hashcode方法 但是我们想要掉的 其实是map 的hascode map.put(this@Mappings.hashCode(),this)//我们需要这么写 } fun add(str: String): Unit = str.stringAdd() }
转载请注明原文地址: https://www.6miu.com/read-59000.html

最新回复(0)