Kotlin常用操作符总结

常用操作符

1、? 操作符

表示对象可能为空,或者对象可以为空

//在变量之后加上 ?,则代表变量可以为空
var name: String? = null

//加在函数返回值类型后边,表示函数方法返回值可以为空
fun getName(): String? {
    ....
}

//如果 b非空,就返回 b.length ,否则返回 null,这个表达式的类型是 Int? 。
//相当于 if not null
b?.length 

2、 ?: 操作符

相当于 if null 执行一个语句

val values = ……
// 如果 values["email"] 为null,则执行 throw IllegalStateException("Email is missing!")
// 反之执行 values["email"]
val email = values["email"] ?: throw IllegalStateException("Email is missing!")

3、 !! 操作符

当对象为null,则抛出空指针(NPE)异常:

val l = b!!.length

4、 .. 操作符

x .. y  
//从x 到y,并且包含x、y值,是一个闭区间运算符
//相对的 until 则是半闭区间运算符,包含 x 不包含 y

5、 in 操作符

in 表示包含在区间中, !in 则不在区间中

if(i in 1..10){ //相当于 i >= 1 && i<= 10
    
}

for(i in 1 until 10)
相当于
for(i = 1,i < 10,i++)

6、 == 与 === 操作符

== 判断值是否相等,

=== 判断引用是否相等

7、 :: 操作符

得到类的 class 对象,创建一个成员引用或者一个类引用

1、得到类的class
val c = MyClass::class

2、函数引用
//声明一个函数
fun isOdd(value: Int) = value%2 != 0
//作为函数类型值传递给另外一个函数
val numbers = listOf(1,2,3)
println(numbers.filter(::isOdd))
//运行结果
[1,3]

如果我们需要使用类的成员函数或扩展函数,它需要是限定的,例如 String::toCharArray。

整体理解就是对函数或者类的一个引用,在上下文中明确函数返回类型,也可以使用该操作符重载函数

8、 @ 操作符

  • 引入一个注解
//声明
annotation class Fancy
//用法
@Fancy class Foo {
    @Fancy fun baz(@Fancy foo: Int): Int {
        return (@Fancy 1)
    }
}
  • 引入或者引用一个循环标签
标签的格式为标识符后跟 @ ,例如:abc@、fooBar@
1、跳出一个双层循环
loop@ for (i in 1..100) {
    for (j in 1..100) {
        if (……) break@loop
    }
}

相当于在 return、continue、break 关键词之后加上 @label,则跳转结束到 @label 处

return@a 1
//当要返一个回值的时候,解析器优先选用标签限制的 return,
//相当于 从标签 @a 返回 1
  • 限定 this 的类型
class A { // 隐式标签 @A
    inner class B { // 隐式标签 @B
        fun Int.foo() { // 隐式标签 @foo
            val a = this@A // A 的 this
            val b = this@B // B 的 this

            val c = this // foo() 的接收者,一个 Int
            val c1 = this@foo // foo() 的接收者,一个 Int

            val funLit = lambda@ fun String.() {
                val d = this // funLit 的接收者
            }


            val funLit2 = { s: String ->
                // foo() 的接收者,因为它包含的 lambda 表达式
                // 没有任何接收者
                val d1 = this
            }
        }
    }
}
  • 引用外部超类
class Bar : Foo() {
    override fun f() { /* …… */ }
    override val x: Int get() = 0
    
    inner class Baz {
        fun g() {
            [email protected]() // 调用 Foo 实现的 f()
            println([email protected]) // 使用 Foo 实现的 x 的 getter
        }
    }
}

-> 操作符

  • 分隔在函数类型中的参数类型与返回类型声明
详细具体可以参考
http://www.kotlincn.net/docs/reference/lambdas.html#%E5%87%BD%E6%95%B0%E7%B1%BB%E5%9E%8B

1、(A,B)-> C 
    表示 接收的类型分别是 参数类型A、参数类型B、返回值类型C 的值

  • 分隔 when 表达式分支的条件与代码体
when (x) {
    1 -> print("x == 1")
    2 -> print("x == 2")
    else -> { // 注意这个块
        print("x is neither 1 nor 2")
    }
}

参考

http://www.kotlincn.net/docs/reference/idioms.html

https://www.kotlincn.net/docs/reference/keyword-reference.html

https://blog.csdn.net/dangnianmingyue_gg/article/details/75305504

你可能感兴趣的:(Kotlin常用操作符总结)