Kotlin语言学习笔记(6)
运算符重载(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)的更多相关文章
- Kotlin语言学习笔记(2)
类(classes) // 类声明 class Invoice { } // 空的类 class Empty // 主体构造器(primary constructor) class Person co ...
- Kotlin语言学习笔记(1)
fun main(args: Array<String>) { println("Hello, World!") } 基本语法 声明常量用val,声明变量用var,声明 ...
- Kotlin语言学习笔记(5)
委托模式(Delegation) 类的委托 interface Base { fun print() } class BaseImpl(val x: Int) : Base { override fu ...
- Kotlin语言学习笔记(3)
数据类(Data Classes) data class User(val name: String, val age: Int) 编译器自动生成的有: equals()/hashCode() toS ...
- Kotlin语言学习笔记(7)
反射 // 反射 val c = MyClass::class val c2 = MyClass::class.java // 获取KClass的引用 val widget: Widget = ... ...
- Kotlin语言学习笔记(4)
函数 // 函数定义及调用 fun double(x: Int): Int { return 2*x } val result = double(2) // 调用方法 Sample().foo() / ...
- HTML语言学习笔记(会更新)
# HTML语言学习笔记(会更新) 一个html文件是由一系列的元素和标签组成的. 标签: 1.<html></html> 表示该文件为超文本标记语言(HTML)编写的.成对出 ...
- 2017-04-21周C语言学习笔记
C语言学习笔记:... --------------------------------- C语言学习笔记:学习程度的高低取决于.自学能力的高低.有的时候生活就是这样的.聪明的人有时候需要.用笨的方法 ...
- 2017-05-4-C语言学习笔记
C语言学习笔记... ------------------------------------ Hello C语言:什么是程序:程序是指:完成某件事的既定方式和过程.计算机中的程序是指:为了让计算机执 ...
随机推荐
- php实现Facebook风格的 time ago函数
php实现Facebook风格的 time ago函数 非常好用,只要把里面的英文替换成中文就行了 英文函数代码如下: <?php function nicetime($date) { if(e ...
- idea引入svn
刚想在idea看一个svn的项目代码,结果发现导入项目后,idea在右下角弹出了Event Log窗口,里面的红色小字 Can't use Subversion command line client ...
- Heritrix3.x自定义扩展Extractor
一.引言: Heritrix3.x与Heritrix1.x版本差异比较大,全新配置模式的引入+扩展接口的变化,同时由于说明文档的匮乏,给Heritrix的开发者带来困惑,前面的文章已经就Heritri ...
- 【FusionCharts学习-1】获取资源
网址 官网: http://www.fusioncharts.com/charts/ 入门学习:http://www.fusioncharts.com/dev/usage-guide/getting ...
- Javascript之类型检测(一)
js中有7种内置类型,这7种类型又分为2大类:基本数据类型和对象(object) 一.检测原始(基本数据:字符串.数字.布尔.null.undefined.symbol)类型. 用typeof检测原始 ...
- vertical-align表单元素垂直对齐
原文地址:http://www.blueidea.com/tech/web/2009/6910.asp 最近的项目涉及到很多表单的制作,特别是复选框(checkbox)和单选框(radio).但是在前 ...
- 解决thinkphp设置session周期无效的问题
thinkphp的session设置周期是无效的:直接的影响就是无法保留用户的登陆状态:用thinkphp开发的项目:关闭浏览器后用户就退出了:即便设置了session周期也没作用:这个bug存在很久 ...
- php使用inotify实现队列处理
php使用inotify实现队列处理参考如下文章:http://blog.jiunile.com/php%E4%BD%BF%E7%94%A8inotify%E5%AE%9E%E7%8E%B0%E9%9 ...
- VS Code 基本介绍 和 快捷键
简介 VSCode是微软推出的一款轻量编辑器,采取了和VS相同的UI界面,搭配合适的插件可以大幅提升前端开发的效率. 布局:左侧是用于展示所要编辑的所有文件和文件夹的文件管理器,依次是:资源管理器,搜 ...
- 6.22-Servlet
一.servlet servlet是运行在服务器端的java程序 jsp专注于显示 servlet处理请求和响应 创建servlet 继承HttpServlet 实现servlet接口 配置servl ...