赞
踩
kotlin高级特性:扩展
Java语言并不支持这扩展,java的扩展是多态 也就是要继承类或者装饰设计模式,kotlin允许为某个类构建扩展方法而不用继承或者装饰
语法: fun 类名.扩展方法名(参数) eg. fun MutableList<Int>.swap(index: Int, index2: Int) {
例子:为list提供交换的扩展方法
- fun MutableList<Int>.swap(index: Int, index2: Int) {
- val any = this[index];
- this[index] = this[index2];
- this[index2] = any;
- }
- val list: MutableList<Int> = mutableListOf(1, 2, 4);
- list.swap(0, 1);
- System.out.println("================>list:" + list);//================>list:[2, 1, 4]
然而针对其他类型的list 却不行
我们可以扩展泛型的list交换方法(当然有人会这么写 MutableList<String>.swap MutableList<Double>.swap......无穷)
- fun <T> MutableList<T>.swap2(index: Int, index2: Int) {
- val any = this[index];
- this[index] = this[index2];
- this[index2] = any;
- }
- val stringList: MutableList<String> = mutableListOf("1", "2", "4");
- /* stringList.swap(0, 1);*/
- stringList.swap2(0, 1);
- System.out.println("================>list2:" + stringList);//================>list:[2, 1, 4]
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。