运算符重载(Operator overloading)

一元运算符

Expression Translated to
+a a.unaryPlus()
-a a.unaryMinus()
!a a.not()
data class Point(val x: Int, val y: Int)
operator fun Point.unaryMinus() = Point(-x, -y)
val point = Point(10, 20)
println(-point) // prints "(-10, -20)"

递增递减运算符

Expression Translated to
a++ a.inc() + see below
a-- a.dec() + see below

算术运算符

Expression Translated to
a + b a.plus(b)
a - b a.minus(b)
a * b a.times(b)
a / b a.div(b)
a % b a.rem(b), a.mod(b) (deprecated)
a..b a.rangeTo(b)
data class Counter(val dayIndex: Int) {
operator fun plus(increment: Int): Counter {
return Counter(dayIndex + increment)
}
}

in 运算符

Expression Translated to
a in b b.contains(a)
a !in b !b.contains(a)

下标存取运算符

Expression Translated to
a[i] a.get(i)
a[i, j] a.get(i, j)
a[i_1, ..., i_n] a.get(i_1, ..., i_n)
a[i] = b a.set(i, b)
a[i, j] = b a.set(i, j, b)
a[i_1, ..., i_n] = b a.set(i_1, ..., i_n, b)

调用运算符

Expression Translated to
a() a.invoke()
a(i) a.invoke(i)
a(i, j) a.invoke(i, j)
a(i_1, ..., i_n) a.invoke(i_1, ..., i_n)

增强运算符

Expression Translated to
a += b a.plusAssign(b)
a -= b a.minusAssign(b)
a *= b a.timesAssign(b)
a /= b a.divAssign(b)
a %= b a.remAssign(b), a.modAssign(b) (deprecated)

相等不等运算符

Expression Translated to
a == b a?.equals(b) ?: (b === null)
a != b !(a?.equals(b) ?: (b === null))

比较运算符

Expression Translated to
a > b a.compareTo(b) > 0
a < b a.compareTo(b) < 0
a >= b a.compareTo(b) >= 0
a <= b a.compareTo(b) <= 0

Null 安全性

// 可空类型和非空类型
var a: String = "abc"
a = null // compilation error
var b: String? = "abc"
b = null // ok
val l = a.length
val l = b.length // error: variable 'b' can be null
// 检查 null
val l = if (b != null) b.length else -1
if (b != null && b.length > 0) {
print("String of length ${b.length}")
} else {
print("Empty string")
}
// 安全调用
b?.length
bob?.department?.head?.name
val listWithNulls: List<String?> = listOf("A", null)
for (item in listWithNulls) {
item?.let { println(it) } // prints A and ignores null
}
// If either `person` or `person.department` is null, the function is not called:
person?.department?.head = managersPool.getManager()
// Elvis运算符
val l: Int = if (b != null) b.length else -1
val l = b?.length ?: -1
fun foo(node: Node): String? {
val parent = node.getParent() ?: return null
val name = node.getName() ?: throw IllegalArgumentException("name expected")
// ...
}
// !! 运算符
val l = b!!.length
// 安全转型
val aInt: Int? = a as? Int
// 可空类型的集合类型
val nullableList: List<Int?> = listOf(1, 2, null, 4)
val intList: List<Int> = nullableList.filterNotNull()

异常(Exceptions)

Kotlin 语言不提供 checked exception

// throw表达式 和 try表达式
throw MyException("Hi There!")
try {
// some code
}
catch (e: SomeException) {
// handler
}
finally {
// optional finally block
}
// try 是表达式
val a: Int? = try { parseInt(input) } catch (e: NumberFormatException) { null }
// throw 表达式的类型是 Nothing
val s = person.name ?: throw IllegalArgumentException("Name required")
val s = person.name ?: fail("Name required")
println(s) // 's' is known to be initialized at this point
val x = null // 'x' has type `Nothing?`
val l = listOf(null) // 'l' has type `List<Nothing?>

注解(Annotations)

注解的参数类型包括:

  • Java的基本类型
  • 字符串
  • 枚举
  • 其他注解
  • 以上类型的数组

使用端的注解包括:

  • file
  • property(Java不可见)
  • field
  • get(getter)
  • set(setter)
  • receiver(扩展函数以及扩展属性的接收者参数)
  • param(主体构造器的参数)
  • setparam(setter的参数)
  • delegate(委托属性)
// 语法
annotation class Fancy
// 详细语法
@Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION,
AnnotationTarget.VALUE_PARAMETER, AnnotationTarget.EXPRESSION)
@Retention(AnnotationRetention.SOURCE)
@MustBeDocumented
annotation class Fancy
// 用法
@Fancy class Foo {
@Fancy fun baz(@Fancy foo: Int): Int {
return (@Fancy 1)
}
}
// 给主体构造器加注解时必须使用constructor关键字
class Foo @Inject constructor(dependency: MyDependency) {
// ...
}
// 给属性存取器加注解
class Foo {
var x: MyDependency? = null
@Inject set
}
// 带参数的注解
annotation class Special(val why: String)
@Special("example") class Foo {}
// 把注解用作其他注解的参数
annotation class ReplaceWith(val expression: String)
annotation class Deprecated(
val message: String,
val replaceWith: ReplaceWith = ReplaceWith(""))
@Deprecated("This function is deprecated, use === instead", ReplaceWith("this === other"))
// 把类用作注解的参数
import kotlin.reflect.KClass
annotation class Ann(val arg1: KClass<*>, val arg2: KClass<out Any>)
@Ann(String::class, Int::class) class MyClass
// 给lambda表达式加上注解
annotation class Suspendable
val f = @Suspendable { Fiber.sleep(10) }
// 使用端的注解
class Example(@field:Ann val foo, // annotate Java field
@get:Ann val bar, // annotate Java getter
@param:Ann val quux) // annotate Java constructor parameter
// 给整个文件加注解
@file:JvmName("Foo")
package org.jetbrains.demo
// Java注解
import org.junit.Test
import org.junit.Assert.*
import org.junit.Rule
import org.junit.rules.* class Tests {
// apply @Rule annotation to property getter
@get:Rule val tempFolder = TemporaryFolder() @Test fun simple() {
val f = tempFolder.newFile()
assertEquals(42, getTheAnswer())
}
}
// ①
// Java
public @interface Ann {
int intValue();
String stringValue();
}
// Kotlin
@Ann(intValue = 1, stringValue = "abc") class C
// ①
// Java
public @interface AnnWithValue {
String value();
}
// Kotlin
@AnnWithValue("abc") class C
// ②
// Java
public @interface AnnWithArrayValue {
String[] value();
}
// Kotlin
@AnnWithArrayValue("abc", "foo", "bar") class C
// ③
// Java
public @interface AnnWithArrayMethod {
String[] names();
}
// Kotlin 1.2+:
@AnnWithArrayMethod(names = ["abc", "foo", "bar"])
class C
// Older Kotlin versions:
@AnnWithArrayMethod(names = arrayOf("abc", "foo", "bar"))
class D
// ④
// Java
public @interface Ann {
int value();
}
// Kotlin
fun foo(ann: Ann) {
val i = ann.value
}

Kotlin语言学习笔记(6)的更多相关文章

  1. Kotlin语言学习笔记(2)

    类(classes) // 类声明 class Invoice { } // 空的类 class Empty // 主体构造器(primary constructor) class Person co ...

  2. Kotlin语言学习笔记(1)

    fun main(args: Array<String>) { println("Hello, World!") } 基本语法 声明常量用val,声明变量用var,声明 ...

  3. Kotlin语言学习笔记(5)

    委托模式(Delegation) 类的委托 interface Base { fun print() } class BaseImpl(val x: Int) : Base { override fu ...

  4. Kotlin语言学习笔记(3)

    数据类(Data Classes) data class User(val name: String, val age: Int) 编译器自动生成的有: equals()/hashCode() toS ...

  5. Kotlin语言学习笔记(7)

    反射 // 反射 val c = MyClass::class val c2 = MyClass::class.java // 获取KClass的引用 val widget: Widget = ... ...

  6. Kotlin语言学习笔记(4)

    函数 // 函数定义及调用 fun double(x: Int): Int { return 2*x } val result = double(2) // 调用方法 Sample().foo() / ...

  7. HTML语言学习笔记(会更新)

    # HTML语言学习笔记(会更新) 一个html文件是由一系列的元素和标签组成的. 标签: 1.<html></html> 表示该文件为超文本标记语言(HTML)编写的.成对出 ...

  8. 2017-04-21周C语言学习笔记

    C语言学习笔记:... --------------------------------- C语言学习笔记:学习程度的高低取决于.自学能力的高低.有的时候生活就是这样的.聪明的人有时候需要.用笨的方法 ...

  9. 2017-05-4-C语言学习笔记

    C语言学习笔记... ------------------------------------ Hello C语言:什么是程序:程序是指:完成某件事的既定方式和过程.计算机中的程序是指:为了让计算机执 ...

随机推荐

  1. PHP 短连接生成算法

    短连接生成类: <?php #短连接生成算法 class Short_Url { #字符表 public static $charset = "0123456789ABCDEFGHIJ ...

  2. Angular 4 重定向路由

    重定向路由: 用户访问一个指定的地址时,将其重新向到另一个指定的地址 (接前面的一节) 配置如下: 之前http://localhost:4200 会进入主页,现在将主页导航改为home,http:/ ...

  3. js去除运营商或者路由器添加的广告脚本

    是不是偶尔发现在家里看网页的时候回插入一个广告,很烦人.开发的网站,上传到了阿里云 oss,设置了域名解析,但是在家里晚上访问的时候,总会在页面添加一个广告,导致页面卡主,一开始以为是路由器的问题,以 ...

  4. 如何更改tomcat7及以上版本内存设置

    http://jingyan.baidu.com/article/295430f1c22a940c7e0050fb.html?qq-pf-to=pcqq.c2c 当在tomcat的webapps文件夹 ...

  5. mysql视图 新手的问答

    ☺ζั͡ޓއއއ๓º♥双٩(•(365335093) 16:03:02 创建的视图能保存多长时间,保存在哪啊 上天&宠儿(961431958) 16:08:59 数据库 上天&宠儿(9 ...

  6. 快速接入PHP微信支付

    微信支付是微信开发中坑最多的一个功能,本文旨在帮助有开发基础的人快速接入微信支付,如果要详细了解微信支付,请看微信支付的开发文档. 再说把开发文档搬到这里来就没必要了.想要快速跑通微信支付的可以继续查 ...

  7. fiddler抓包HTTPS请求

    fiddler抓包HTTPS请求 标签: fiddlerhttps抓包 2016-03-29 21:24 23293人阅读 评论(2) 收藏 举报  分类: 不登高山不知天之高也(1)  版权声明:本 ...

  8. VBA注释临时

    Sub shishi() '按ABCDE为多选题定义答案; 'A.沙利度胺 B.异烟肼 C.利福平 'd.氯法齐明 E.氨苯砜 '46.各型麻风病的首选药物为(D) 'A.沙利度胺 B.异烟肼 C.利 ...

  9. SpringMVC 获取请求参数

    1.获取Request response对象 在SpringMVC的注解开发中,可以选择性的接收Request和Response对象来使用 2.获取request对象请求参数 a.通过request对 ...

  10. js关于a++ 与++a

    var a=6; var b=a++; 此时a的值是7;a++的值是7;b的值是6; var c=8; var d=--c; 此时c的值是7;--c的值是6;d的值是7;