事实上,Kotlin 并未使用|作为按位或运算符,取而代之的时 infix functionor: /** Performs a bitwise OR operation between the two values. */publicinfixfunor(other:Int):Int 最后需要注意的一点是,上面的所有函数全部为顶层函数(Top Level Function),这可以方便脚本直接调用这些函数,而不需要指定命名空间。
我们可以使用库函数array()来创建一个包含数值的数组, array(1, 2, 3) 创建了 array [1, 2, 3]. 或者, arrayOfNulls()可以创建一个指定大小,元素都为空的数组。 或者使用函数来创建一个数组: 代码语言:javascript 复制 // Creates an Array<String> with values ["0", "1", "4", "9", "16"]...
class Point(val x: Int, val y: Int) : Comparable<Point> { override operator fun compareTo(other: Point): Int { return compareValuesBy(this, other, { it.x }, { it.y }) } } val p1 = Point(1, 2) val p2 = Point(3, 4) p1 < p2 // true,因为 p1 的坐标小于 p2 的坐标 ...
. return !this.isEmpty() ... } >>> "".notEmpty() false >>> "123".notEmpty() true 下面代码为 MutableList<Int> 添加一个swap 函数:fun MutableList<Int>.swap(index1: Int, index2: Int) { val tmp = this[index1] // this对应该列表 this[index1] = this[index2] this[index2] = ...
override fun compareTo(other: Person): Int {returncompareValuesBy(this, other, Person::firstName, Person::lastName)//这里传入的参数是按照顺序,比较的参数也是按照顺序} } 四、通过下标访问元素:get和set 1、val value = map[key] 类似这种方式即:map再加方括号的形式 ...
1 2 4 5 标签(Label) 介绍:在Kotlin中任何表达式都可以使用标签来标记.标签的格式为标识符+@ 符号组成.标签的标识符是可以自定义. 而通常使用标签会配合Break,Continue或者return来使用. 因为通过标签可以决定方法执行后的跳转对象. 实例1: 代码语言:javascript 复制 zin@ for (i in 1..10) { print("i:...
firstName相同再比较lastNamedataclassPerson(valfirstName:String,vallastName:String):Comparable<Person>{overridefuncompareTo(other:Person):Int{returncompareValuesBy(this,other,Person::firstName,Person::lastName)}}valperson=Person("Li","m1Ku")valperson2=Person("wang","rick")println(person<person2)>...
return 2*x } val result = double(2) // 调用方法 Stream().read() // create instance of class Stream and call read() // 参数语法 fun powerOf(number: Int, exponent: Int): Int { /*...*/ } // 参数声明时可以带拖尾逗号 fun powerOf( number: Int, exponent: Int, // trailing comm...
2. 熟悉Java生态 3. 了解一些特性背后的实现 1. 2. 3. 4. 5. 6. Kotlin的数据类型 var与val 的区别 var为可变变量,val相当于只读变量,如同java 中的final 一样,val 创建时必须被初始化。 1. 2. 1.认识基本类型 2.初步认识类及其相关概念
Creates an outputFlowwhich sequentially emits all values from the first givenFlowand then moves on to the next. concat( flow1=flowOf(1,2,3), flow2=flowOf(4,5,6) ).collect {println("concat:$it") } Output: concat: 1 concat: 2 ...