运算符重载(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. Mfs+drbd+keepalived实现mfs系统高可用

    http://blog.sina.com.cn/s/blog_53c654720102wo1k.html Moosefs分布式文件系统是一个易用的系统,但其只有在Pro版中提供了master的高可用方 ...

  2. [boost] : lightweight_test库

    lightweight_test轻量级单元测试框架, 只支持最基本的单元测试, 不支持测试用例, 测试套件的概念, 简单小巧, 适合要求不高或者快速测试的工作. 基本用法 需要包含头文件#includ ...

  3. 【shell】正则表达式语法

    一个正则表达式就是由普通字符(例如字符 a 到 z)以及特殊字符(称为元字符)组成的文字模式.该模式描述在查找文字主体时待匹配的一个或多个字符串.正则表达式作为一个模板,将某个字符模式与所搜索的字符串 ...

  4. css display table使用小例子实验

    display的下面: table: 此元素会作为块级表格来显示(类似 <table>),表格前后带有换行符. table-row 此元素会作为一个表格行显示(类似 <tr>) ...

  5. 学习笔记之100 TOP Ikm C++ Online Test Questions

    100 TOP Ikm C++ Online Test Questions 2017 http://interviewquestionstutorials.com/tag/100-top-ikm-c- ...

  6. [转]批处理遍历文件夹生成 html 文件

    [转自] http://www.360doc.com/content/15/0205/20/21861372_446525665.shtml :: 自动将指定文件夹中的图片写入到 html 文件中 @ ...

  7. pyplot 绘图与可视化

    1. 基本使用 #!/usr/bin/env python # coding=utf-8 import matplotlib.pyplot as plt from numpy.random impor ...

  8. Spark学习笔记1:Spark概览

    Spark是一个用来实现快速而通用的集群计算的平台. Spark项目包含多个紧密集成的组件.Spark的核心是一个对由很多计算任务组成的,运行在多个工作机器或者是一个计算集群上的应用进行调度,分发以及 ...

  9. C++多线程同步之Mutex(互斥量)

    原文链接: http://blog.csdn.net/olansefengye1/article/details/53086141 一.互斥量Mutex同步多线程 1.Win32平台 相关函数和头文件 ...

  10. PHP mysqli_fetch_object() 函数实例讲解

    定义和用法 mysqli_fetch_object() 函数从结果集中取得当前行,并作为对象返回. 注释:该函数返回的字段名是区分大小写的. 语法 mysqli_fetch_object(result ...