3.7 语法与标识符
我们知道,任何一门编程语言都会有一些自己专用的关键字、符号以及规定的语法规则等等。程序员们使用这些基础词汇和语法规则来表达算法步骤,也就是写代码的过程。
词法分析是编译器对源码进行编译的基础步骤之一。词法分析是将源程序读入的字符序列,按照一定的规则转换成词法单元(Token)序列的过程。词法单元是语言中具有独立意义的最小单元,包括修饰符、关键字、常数、运算符、边界符等等。
3.7.1 修饰符
在Kotlin源码工程中的kotlin/grammar/src/modifiers.grm文件中,描述了Kotlin语言的修饰符,我们在此作简要注释说明:
1. /**
2. ## Modifiers
3. */
5. modifiers
6. : (modifier | annotations)*
7. ;
9. typeModifiers
10. : (suspendModifier | annotations)*
11. ;
13. modifier
14. : classModifier
15. : accessModifier
16. : varianceAnnotation
17. : memberModifier
18. : parameterModifier
19. : typeParameterModifier
20. : functionModifier
21. : propertyModifier
22. ;
24. classModifier 类修饰符
25. : "abstract" 抽象类
26. : "final" 不可被继承final类
27. : "enum" 枚举类
28. : "open" 可继承open类
29. : "annotation" 注解类
30. : "sealed" 密封类
31. : "data" 数据类
32. ;
34. memberModifier
35. : "override" 重写函数
36. : "open" 可被重写
37. : "final" 不可被重写
38. : "abstract" 抽象函数
39. : "lateinit" 后期初始化
40. ;
42. accessModifier 访问权限控制, 默认是public
43. : "private"
44. : "protected"
45. : "public"
46. : "internal" 整个模块内(模块(module)是指一起编译的一组 Kotlin 源代码文件: 例如,一个 IntelliJ IDEA 模块,一个 Maven 工程, 或 Gradle 工程,通过 Ant 任务的一次调用编译的一组文件等)可访问
47. ;
49. varianceAnnotation 泛型可变性
50. : "in"
51. : "out"
52. ;
54. parameterModifier
55. : "noinline"
56. : "crossinline"
57. : "vararg" 变长参数
58. ;
60. typeParameterModifier
61. : "reified"
62. ;
64. functionModifier
65. : "tailrec" 尾递归
66. : "operator"
67. : "infix"
68. : "inline"
69. : "external"
70. : suspendModifier
71. ;
73. propertyModifier
74. : "const"
75. ;
77. suspendModifier
78. : "suspend"
79. ;
这些修饰符的完整定义,在kotlin/compiler/frontend/src/org/jetbrains/kotlin/lexer/KtTokens.java源码中:
1. KtModifierKeywordToken[] MODIFIER_KEYWORDS_ARRAY =
2. new KtModifierKeywordToken[] {
3. ABSTRACT_KEYWORD, ENUM_KEYWORD, OPEN_KEYWORD, INNER_KEYWORD, OVERRIDE_KEYWORD, PRIVATE_KEYWORD,
4. PUBLIC_KEYWORD, INTERNAL_KEYWORD, PROTECTED_KEYWORD, OUT_KEYWORD, IN_KEYWORD, FINAL_KEYWORD, VARARG_KEYWORD,
5. REIFIED_KEYWORD, COMPANION_KEYWORD, SEALED_KEYWORD, LATEINIT_KEYWORD,
6. DATA_KEYWORD, INLINE_KEYWORD, NOINLINE_KEYWORD, TAILREC_KEYWORD, EXTERNAL_KEYWORD, ANNOTATION_KEYWORD, CROSSINLINE_KEYWORD,
7. CONST_KEYWORD, OPERATOR_KEYWORD, INFIX_KEYWORD, SUSPEND_KEYWORD, HEADER_KEYWORD, IMPL_KEYWORD
8. };
10. TokenSet MODIFIER_KEYWORDS = TokenSet.create(MODIFIER_KEYWORDS_ARRAY);
12. TokenSet TYPE_MODIFIER_KEYWORDS = TokenSet.create(SUSPEND_KEYWORD);
13. TokenSet TYPE_ARGUMENT_MODIFIER_KEYWORDS = TokenSet.create(IN_KEYWORD, OUT_KEYWORD);
14. TokenSet RESERVED_VALUE_PARAMETER_MODIFIER_KEYWORDS = TokenSet.create(OUT_KEYWORD, VARARG_KEYWORD);
16. TokenSet VISIBILITY_MODIFIERS = TokenSet.create(PRIVATE_KEYWORD, PUBLIC_KEYWORD, INTERNAL_KEYWORD, PROTECTED_KEYWORD);
3.7.2 关键字(保留字)
1. TokenSet KEYWORDS = TokenSet.create(PACKAGE_KEYWORD, AS_KEYWORD, TYPE_ALIAS_KEYWORD, CLASS_KEYWORD, INTERFACE_KEYWORD,
2. THIS_KEYWORD, SUPER_KEYWORD, VAL_KEYWORD, VAR_KEYWORD, FUN_KEYWORD, FOR_KEYWORD,
3. NULL_KEYWORD,
4. TRUE_KEYWORD, FALSE_KEYWORD, IS_KEYWORD,
5. IN_KEYWORD, THROW_KEYWORD, RETURN_KEYWORD, BREAK_KEYWORD, CONTINUE_KEYWORD, OBJECT_KEYWORD, IF_KEYWORD,
6. ELSE_KEYWORD, WHILE_KEYWORD, DO_KEYWORD, TRY_KEYWORD, WHEN_KEYWORD,
7. NOT_IN, NOT_IS, AS_SAFE,
8. TYPEOF_KEYWORD
9. );
11. TokenSet SOFT_KEYWORDS = TokenSet.create(FILE_KEYWORD, IMPORT_KEYWORD, WHERE_KEYWORD, BY_KEYWORD, GET_KEYWORD,
12. SET_KEYWORD, ABSTRACT_KEYWORD, ENUM_KEYWORD, OPEN_KEYWORD, INNER_KEYWORD,
13. OVERRIDE_KEYWORD, PRIVATE_KEYWORD, PUBLIC_KEYWORD, INTERNAL_KEYWORD, PROTECTED_KEYWORD,
14. CATCH_KEYWORD, FINALLY_KEYWORD, OUT_KEYWORD, FINAL_KEYWORD, VARARG_KEYWORD, REIFIED_KEYWORD,
15. DYNAMIC_KEYWORD, COMPANION_KEYWORD, CONSTRUCTOR_KEYWORD, INIT_KEYWORD, SEALED_KEYWORD,
16. FIELD_KEYWORD, PROPERTY_KEYWORD, RECEIVER_KEYWORD, PARAM_KEYWORD, SETPARAM_KEYWORD,
17. DELEGATE_KEYWORD,
18. LATEINIT_KEYWORD,
19. DATA_KEYWORD, INLINE_KEYWORD, NOINLINE_KEYWORD, TAILREC_KEYWORD, EXTERNAL_KEYWORD,
20. ANNOTATION_KEYWORD, CROSSINLINE_KEYWORD, CONST_KEYWORD, OPERATOR_KEYWORD, INFIX_KEYWORD,
21. SUSPEND_KEYWORD, HEADER_KEYWORD, IMPL_KEYWORD
22. );
其中,对应的关键字如下:
1. KtKeywordToken PACKAGE_KEYWORD = KtKeywordToken.keyword("package");
2. KtKeywordToken AS_KEYWORD = KtKeywordToken.keyword("as");
3. KtKeywordToken TYPE_ALIAS_KEYWORD = KtKeywordToken.keyword("typealias");
4. KtKeywordToken CLASS_KEYWORD = KtKeywordToken.keyword("class");
5. KtKeywordToken THIS_KEYWORD = KtKeywordToken.keyword("this");
6. KtKeywordToken SUPER_KEYWORD = KtKeywordToken.keyword("super");
7. KtKeywordToken VAL_KEYWORD = KtKeywordToken.keyword("val");
8. KtKeywordToken VAR_KEYWORD = KtKeywordToken.keyword("var");
9. KtKeywordToken FUN_KEYWORD = KtKeywordToken.keyword("fun");
10. KtKeywordToken FOR_KEYWORD = KtKeywordToken.keyword("for");
11. KtKeywordToken NULL_KEYWORD = KtKeywordToken.keyword("null");
12. KtKeywordToken TRUE_KEYWORD = KtKeywordToken.keyword("true");
13. KtKeywordToken FALSE_KEYWORD = KtKeywordToken.keyword("false");
14. KtKeywordToken IS_KEYWORD = KtKeywordToken.keyword("is");
15. KtModifierKeywordToken IN_KEYWORD = KtModifierKeywordToken.keywordModifier("in");
16. KtKeywordToken THROW_KEYWORD = KtKeywordToken.keyword("throw");
17. KtKeywordToken RETURN_KEYWORD = KtKeywordToken.keyword("return");
18. KtKeywordToken BREAK_KEYWORD = KtKeywordToken.keyword("break");
19. KtKeywordToken CONTINUE_KEYWORD = KtKeywordToken.keyword("continue");
20. KtKeywordToken OBJECT_KEYWORD = KtKeywordToken.keyword("object");
21. KtKeywordToken IF_KEYWORD = KtKeywordToken.keyword("if");
22. KtKeywordToken TRY_KEYWORD = KtKeywordToken.keyword("try");
23. KtKeywordToken ELSE_KEYWORD = KtKeywordToken.keyword("else");
24. KtKeywordToken WHILE_KEYWORD = KtKeywordToken.keyword("while");
25. KtKeywordToken DO_KEYWORD = KtKeywordToken.keyword("do");
26. KtKeywordToken WHEN_KEYWORD = KtKeywordToken.keyword("when");
27. KtKeywordToken INTERFACE_KEYWORD = KtKeywordToken.keyword("interface");
29. // Reserved for future use:
30. KtKeywordToken TYPEOF_KEYWORD = KtKeywordToken.keyword("typeof");
31. ...
32. KtKeywordToken FILE_KEYWORD = KtKeywordToken.softKeyword("file");
33. KtKeywordToken FIELD_KEYWORD = KtKeywordToken.softKeyword("field");
34. KtKeywordToken PROPERTY_KEYWORD = KtKeywordToken.softKeyword("property");
35. KtKeywordToken RECEIVER_KEYWORD = KtKeywordToken.softKeyword("receiver");
36. KtKeywordToken PARAM_KEYWORD = KtKeywordToken.softKeyword("param");
37. KtKeywordToken SETPARAM_KEYWORD = KtKeywordToken.softKeyword("setparam");
38. KtKeywordToken DELEGATE_KEYWORD = KtKeywordToken.softKeyword("delegate");
39. KtKeywordToken IMPORT_KEYWORD = KtKeywordToken.softKeyword("import");
40. KtKeywordToken WHERE_KEYWORD = KtKeywordToken.softKeyword("where");
41. KtKeywordToken BY_KEYWORD = KtKeywordToken.softKeyword("by");
42. KtKeywordToken GET_KEYWORD = KtKeywordToken.softKeyword("get");
43. KtKeywordToken SET_KEYWORD = KtKeywordToken.softKeyword("set");
44. KtKeywordToken CONSTRUCTOR_KEYWORD = KtKeywordToken.softKeyword("constructor");
45. KtKeywordToken INIT_KEYWORD = KtKeywordToken.softKeyword("init");
47. KtModifierKeywordToken ABSTRACT_KEYWORD = KtModifierKeywordToken.softKeywordModifier("abstract");
48. KtModifierKeywordToken ENUM_KEYWORD = KtModifierKeywordToken.softKeywordModifier("enum");
49. KtModifierKeywordToken OPEN_KEYWORD = KtModifierKeywordToken.softKeywordModifier("open");
50. KtModifierKeywordToken INNER_KEYWORD = KtModifierKeywordToken.softKeywordModifier("inner");
51. KtModifierKeywordToken OVERRIDE_KEYWORD = KtModifierKeywordToken.softKeywordModifier("override");
52. KtModifierKeywordToken PRIVATE_KEYWORD = KtModifierKeywordToken.softKeywordModifier("private");
53. KtModifierKeywordToken PUBLIC_KEYWORD = KtModifierKeywordToken.softKeywordModifier("public");
54. KtModifierKeywordToken INTERNAL_KEYWORD = KtModifierKeywordToken.softKeywordModifier("internal");
55. KtModifierKeywordToken PROTECTED_KEYWORD = KtModifierKeywordToken.softKeywordModifier("protected");
56. KtKeywordToken CATCH_KEYWORD = KtKeywordToken.softKeyword("catch");
57. KtModifierKeywordToken OUT_KEYWORD = KtModifierKeywordToken.softKeywordModifier("out");
58. KtModifierKeywordToken VARARG_KEYWORD = KtModifierKeywordToken.softKeywordModifier("vararg");
59. KtModifierKeywordToken REIFIED_KEYWORD = KtModifierKeywordToken.softKeywordModifier("reified");
60. KtKeywordToken DYNAMIC_KEYWORD = KtKeywordToken.softKeyword("dynamic");
61. KtModifierKeywordToken COMPANION_KEYWORD = KtModifierKeywordToken.softKeywordModifier("companion");
62. KtModifierKeywordToken SEALED_KEYWORD = KtModifierKeywordToken.softKeywordModifier("sealed");
64. KtModifierKeywordToken DEFAULT_VISIBILITY_KEYWORD = PUBLIC_KEYWORD;
66. KtKeywordToken FINALLY_KEYWORD = KtKeywordToken.softKeyword("finally");
67. KtModifierKeywordToken FINAL_KEYWORD = KtModifierKeywordToken.softKeywordModifier("final");
69. KtModifierKeywordToken LATEINIT_KEYWORD = KtModifierKeywordToken.softKeywordModifier("lateinit");
71. KtModifierKeywordToken DATA_KEYWORD = KtModifierKeywordToken.softKeywordModifier("data");
72. KtModifierKeywordToken INLINE_KEYWORD = KtModifierKeywordToken.softKeywordModifier("inline");
73. KtModifierKeywordToken NOINLINE_KEYWORD = KtModifierKeywordToken.softKeywordModifier("noinline");
74. KtModifierKeywordToken TAILREC_KEYWORD = KtModifierKeywordToken.softKeywordModifier("tailrec");
75. KtModifierKeywordToken EXTERNAL_KEYWORD = KtModifierKeywordToken.softKeywordModifier("external");
76. KtModifierKeywordToken ANNOTATION_KEYWORD = KtModifierKeywordToken.softKeywordModifier("annotation");
77. KtModifierKeywordToken CROSSINLINE_KEYWORD = KtModifierKeywordToken.softKeywordModifier("crossinline");
78. KtModifierKeywordToken OPERATOR_KEYWORD = KtModifierKeywordToken.softKeywordModifier("operator");
79. KtModifierKeywordToken INFIX_KEYWORD = KtModifierKeywordToken.softKeywordModifier("infix");
81. KtModifierKeywordToken CONST_KEYWORD = KtModifierKeywordToken.softKeywordModifier("const");
83. KtModifierKeywordToken SUSPEND_KEYWORD = KtModifierKeywordToken.softKeywordModifier("suspend");
85. KtModifierKeywordToken HEADER_KEYWORD = KtModifierKeywordToken.softKeywordModifier("header");
86. KtModifierKeywordToken IMPL_KEYWORD = KtModifierKeywordToken.softKeywordModifier("impl");
this 关键字
this关键字持有当前对象的引用。我们可以使用this来引用变量或者成员函数,也可以使用return this,来返回某个类的引用。
代码示例
1. class ThisDemo {
2. val thisis = "THIS IS"
4. fun whatIsThis(): ThisDemo {
5. println(this.thisis) //引用变量
6. this.howIsThis()// 引用成员函数
7. return this // 返回此类的引用
8. }
10. fun howIsThis(){
11. println("HOW IS THIS ?")
12. }
13. }
测试代码
1. @Test
2. fun testThisDemo(){
3. val demo = ThisDemo()
4. println(demo.whatIsThis())
5. }
输出
1. THIS IS
2. HOW IS THIS ?
3. com.easy.kotlin.ThisDemo@475232fc
在类的成员中,this 指向的是该类的当前对象。
在扩展函数或者带接收者的函数字面值中, this 表示在点左侧传递的 接收者参数。
代码示例:
1. >>> val sum = fun Int.(x:Int):Int = this + x
2. >>> sum
3. kotlin.Int.(kotlin.Int) -> kotlin.Int
4. >>> 1.sum(1)
5. 2
6. >>> val concat = fun String.(x:Any) = this + x
7. >>> "abc".concat(123)
8. abc123
9. >>> "abc".concat(true)
10. abctrue
如果 this 没有限定符,它指的是最内层的包含它的作用域。如果我们想要引用其他作用域中的 this,可以使用 this@label 标签。
代码示例:
1. class Outer {
2. val oh = "Oh!"
4. inner class Inner {
6. fun m() {
7. val outer = this@Outer
8. val inner = this@Inner
9. val pthis = this
10. println("outer=" + outer)
11. println("inner=" + inner)
12. println("pthis=" + pthis)
13. println(this@Outer.oh)
15. val fun1 = hello@ fun String.() {
16. val d1 = this // fun1 的接收者
17. println("d1" + d1)
18. }
20. val fun2 = { s: String ->
21. val d2 = this
22. println("d2=" + d2)
23. }
25. "abc".fun1()
27. fun2
29. }
30. }
31. }
测试代码:
1. @Test
2. fun testThisKeyWord() {
3. val outer = Outer()
4. outer.Inner().m()
5. }
输出
1. outer=com.easy.kotlin.Outer@5114e183
2. inner=com.easy.kotlin.Outer$Inner@5aa8ac7f
3. pthis=com.easy.kotlin.Outer$Inner@5aa8ac7f
4. Oh!
5. d1abc
super 关键字
super关键字持有指向其父类的引用。
代码示例:
1. open class Father {
2. open val firstName = "Chen"
3. open val lastName = "Jason"
5. fun ff() {
6. println("FFF")
7. }
8. }
10. class Son : Father {
11. override var firstName = super.firstName
12. override var lastName = "Jack"
14. constructor(lastName: String) {
15. this.lastName = lastName
16. }
18. fun love() {
19. super.ff() // 调用父类方法
20. println(super.firstName + " " + super.lastName + " Love " + this.firstName + " " + this.lastName)
21. }
22. }
测试代码
1. @Test
2. fun testSuperKeyWord() {
3. val son = Son("Harry")
4. son.love()
5. }
输出
1. FFF
2. Chen Jason Love Chen Harry
3.7.3 操作符和操作符的重载
Kotlin 允许我们为自己的类型提供预定义的一组操作符的实现。这些操作符具有固定的符号表示(如 + 或 *)和固定的优先级。这些操作符的符号定义如下:
1. KtSingleValueToken LBRACKET = new KtSingleValueToken("LBRACKET", "[");
2. KtSingleValueToken RBRACKET = new KtSingleValueToken("RBRACKET", "]");
3. KtSingleValueToken LBRACE = new KtSingleValueToken("LBRACE", "{");
4. KtSingleValueToken RBRACE = new KtSingleValueToken("RBRACE", "}");
5. KtSingleValueToken LPAR = new KtSingleValueToken("LPAR", "(");
6. KtSingleValueToken RPAR = new KtSingleValueToken("RPAR", ")");
7. KtSingleValueToken DOT = new KtSingleValueToken("DOT", ".");
8. KtSingleValueToken PLUSPLUS = new KtSingleValueToken("PLUSPLUS", "++");
9. KtSingleValueToken MINUSMINUS = new KtSingleValueToken("MINUSMINUS", "--");
10. KtSingleValueToken MUL = new KtSingleValueToken("MUL", "*");
11. KtSingleValueToken PLUS = new KtSingleValueToken("PLUS", "+");
12. KtSingleValueToken MINUS = new KtSingleValueToken("MINUS", "-");
13. KtSingleValueToken EXCL = new KtSingleValueToken("EXCL", "!");
14. KtSingleValueToken DIV = new KtSingleValueToken("DIV", "/");
15. KtSingleValueToken PERC = new KtSingleValueToken("PERC", "%");
16. KtSingleValueToken LT = new KtSingleValueToken("LT", "<");
17. KtSingleValueToken GT = new KtSingleValueToken("GT", ">");
18. KtSingleValueToken LTEQ = new KtSingleValueToken("LTEQ", "<=");
19. KtSingleValueToken GTEQ = new KtSingleValueToken("GTEQ", ">=");
20. KtSingleValueToken EQEQEQ = new KtSingleValueToken("EQEQEQ", "===");
21. KtSingleValueToken ARROW = new KtSingleValueToken("ARROW", "->");
22. KtSingleValueToken DOUBLE_ARROW = new KtSingleValueToken("DOUBLE_ARROW", "=>");
23. KtSingleValueToken EXCLEQEQEQ = new KtSingleValueToken("EXCLEQEQEQ", "!==");
24. KtSingleValueToken EQEQ = new KtSingleValueToken("EQEQ", "==");
25. KtSingleValueToken EXCLEQ = new KtSingleValueToken("EXCLEQ", "!=");
26. KtSingleValueToken EXCLEXCL = new KtSingleValueToken("EXCLEXCL", "!!");
27. KtSingleValueToken ANDAND = new KtSingleValueToken("ANDAND", "&&");
28. KtSingleValueToken OROR = new KtSingleValueToken("OROR", "||");
29. KtSingleValueToken SAFE_ACCESS = new KtSingleValueToken("SAFE_ACCESS", "?.");
30. KtSingleValueToken ELVIS = new KtSingleValueToken("ELVIS", "?:");
31. KtSingleValueToken QUEST = new KtSingleValueToken("QUEST", "?");
32. KtSingleValueToken COLONCOLON = new KtSingleValueToken("COLONCOLON", "::");
33. KtSingleValueToken COLON = new KtSingleValueToken("COLON", ":");
34. KtSingleValueToken SEMICOLON = new KtSingleValueToken("SEMICOLON", ";");
35. KtSingleValueToken DOUBLE_SEMICOLON = new KtSingleValueToken("DOUBLE_SEMICOLON", ";;");
36. KtSingleValueToken RANGE = new KtSingleValueToken("RANGE", "..");
37. KtSingleValueToken EQ = new KtSingleValueToken("EQ", "=");
38. KtSingleValueToken MULTEQ = new KtSingleValueToken("MULTEQ", "*=");
39. KtSingleValueToken DIVEQ = new KtSingleValueToken("DIVEQ", "/=");
40. KtSingleValueToken PERCEQ = new KtSingleValueToken("PERCEQ", "%=");
41. KtSingleValueToken PLUSEQ = new KtSingleValueToken("PLUSEQ", "+=");
42. KtSingleValueToken MINUSEQ = new KtSingleValueToken("MINUSEQ", "-=");
43. KtKeywordToken NOT_IN = KtKeywordToken.keyword("NOT_IN", "!in");
44. KtKeywordToken NOT_IS = KtKeywordToken.keyword("NOT_IS", "!is");
45. KtSingleValueToken HASH = new KtSingleValueToken("HASH", "#");
46. KtSingleValueToken AT = new KtSingleValueToken("AT", "@");
48. KtSingleValueToken COMMA = new KtSingleValueToken("COMMA", ",");
3.7.4 操作符优先级(Precedence)
| 优先级 | 标题 | 符号 |
|---|---|---|
| 最高 | 后缀(Postfix ) | ++, --, ., ?., ? |
| 前缀(Prefix) | -, +, ++, --, !, labelDefinition@ |
|
| 右手类型运算(Type RHS,right-hand side class type (RHS) ) | :, as, as? |
|
| 乘除取余(Multiplicative) | *, /, % |
|
| 加减(Additive ) | +, - |
|
| 区间范围(Range) | .. |
|
| Infix函数 | 例如,给Int定义扩展 infix fun Int.shl(x: Int): Int {...},这样调用 1 shl 2,等同于1.shl(2) |
|
| Elvis操作符 | ?: |
|
| 命名检查符(Named checks) | in, !in, is, !is |
|
| 比较大小(Comparison) | <, >, <=, >= |
|
| 相等性判断(Equality) | ==, \!== |
|
| 与 (Conjunction) | && |
|
| 或 (Disjunction) | ll |
|
| 最低 | 赋值(Assignment) | =, +=, -=, *=, /=, %= |
注:Markdown表格语法:ll是||。
为实现这些的操作符,Kotlin为二元操作符左侧的类型和一元操作符的参数类型,提供了相应的函数或扩展函数。
例如在kotlin/core/builtins/native/kotlin/Primitives.kt代码中,对基本类型Int的操作符的实现代码如下
1. public class Int private constructor() : Number(), Comparable<Int> {
2. ...
4. /**
5. * Compares this value with the specified value for order.
6. * Returns zero if this value is equal to the specified other value, a negative number if it's less than other,
7. * or a positive number if it's greater than other.
8. */
9. public operator fun compareTo(other: Byte): Int
11. /**
12. * Compares this value with the specified value for order.
13. * Returns zero if this value is equal to the specified other value, a negative number if it's less than other,
14. * or a positive number if it's greater than other.
15. */
16. public operator fun compareTo(other: Short): Int
18. /**
19. * Compares this value with the specified value for order.
20. * Returns zero if this value is equal to the specified other value, a negative number if it's less than other,
21. * or a positive number if it's greater than other.
22. */
23. public override operator fun compareTo(other: Int): Int
25. /**
26. * Compares this value with the specified value for order.
27. * Returns zero if this value is equal to the specified other value, a negative number if it's less than other,
28. * or a positive number if it's greater than other.
29. */
30. public operator fun compareTo(other: Long): Int
32. /**
33. * Compares this value with the specified value for order.
34. * Returns zero if this value is equal to the specified other value, a negative number if it's less than other,
35. * or a positive number if it's greater than other.
36. */
37. public operator fun compareTo(other: Float): Int
39. /**
40. * Compares this value with the specified value for order.
41. * Returns zero if this value is equal to the specified other value, a negative number if it's less than other,
42. * or a positive number if it's greater than other.
43. */
44. public operator fun compareTo(other: Double): Int
46. /** Adds the other value to this value. */
47. public operator fun plus(other: Byte): Int
48. /** Adds the other value to this value. */
49. public operator fun plus(other: Short): Int
50. /** Adds the other value to this value. */
51. public operator fun plus(other: Int): Int
52. /** Adds the other value to this value. */
53. public operator fun plus(other: Long): Long
54. /** Adds the other value to this value. */
55. public operator fun plus(other: Float): Float
56. /** Adds the other value to this value. */
57. public operator fun plus(other: Double): Double
59. /** Subtracts the other value from this value. */
60. public operator fun minus(other: Byte): Int
61. /** Subtracts the other value from this value. */
62. public operator fun minus(other: Short): Int
63. /** Subtracts the other value from this value. */
64. public operator fun minus(other: Int): Int
65. /** Subtracts the other value from this value. */
66. public operator fun minus(other: Long): Long
67. /** Subtracts the other value from this value. */
68. public operator fun minus(other: Float): Float
69. /** Subtracts the other value from this value. */
70. public operator fun minus(other: Double): Double
72. /** Multiplies this value by the other value. */
73. public operator fun times(other: Byte): Int
74. /** Multiplies this value by the other value. */
75. public operator fun times(other: Short): Int
76. /** Multiplies this value by the other value. */
77. public operator fun times(other: Int): Int
78. /** Multiplies this value by the other value. */
79. public operator fun times(other: Long): Long
80. /** Multiplies this value by the other value. */
81. public operator fun times(other: Float): Float
82. /** Multiplies this value by the other value. */
83. public operator fun times(other: Double): Double
85. /** Divides this value by the other value. */
86. public operator fun div(other: Byte): Int
87. /** Divides this value by the other value. */
88. public operator fun div(other: Short): Int
89. /** Divides this value by the other value. */
90. public operator fun div(other: Int): Int
91. /** Divides this value by the other value. */
92. public operator fun div(other: Long): Long
93. /** Divides this value by the other value. */
94. public operator fun div(other: Float): Float
95. /** Divides this value by the other value. */
96. public operator fun div(other: Double): Double
98. /** Calculates the remainder of dividing this value by the other value. */
99. @Deprecated("Use rem(other) instead", ReplaceWith("rem(other)"), DeprecationLevel.WARNING)
100. public operator fun mod(other: Byte): Int
101. /** Calculates the remainder of dividing this value by the other value. */
102. @Deprecated("Use rem(other) instead", ReplaceWith("rem(other)"), DeprecationLevel.WARNING)
103. public operator fun mod(other: Short): Int
104. /** Calculates the remainder of dividing this value by the other value. */
105. @Deprecated("Use rem(other) instead", ReplaceWith("rem(other)"), DeprecationLevel.WARNING)
106. public operator fun mod(other: Int): Int
107. /** Calculates the remainder of dividing this value by the other value. */
108. @Deprecated("Use rem(other) instead", ReplaceWith("rem(other)"), DeprecationLevel.WARNING)
109. public operator fun mod(other: Long): Long
110. /** Calculates the remainder of dividing this value by the other value. */
111. @Deprecated("Use rem(other) instead", ReplaceWith("rem(other)"), DeprecationLevel.WARNING)
112. public operator fun mod(other: Float): Float
113. /** Calculates the remainder of dividing this value by the other value. */
114. @Deprecated("Use rem(other) instead", ReplaceWith("rem(other)"), DeprecationLevel.WARNING)
115. public operator fun mod(other: Double): Double
117. /** Calculates the remainder of dividing this value by the other value. */
118. @SinceKotlin("1.1")
119. public operator fun rem(other: Byte): Int
120. /** Calculates the remainder of dividing this value by the other value. */
121. @SinceKotlin("1.1")
122. public operator fun rem(other: Short): Int
123. /** Calculates the remainder of dividing this value by the other value. */
124. @SinceKotlin("1.1")
125. public operator fun rem(other: Int): Int
126. /** Calculates the remainder of dividing this value by the other value. */
127. @SinceKotlin("1.1")
128. public operator fun rem(other: Long): Long
129. /** Calculates the remainder of dividing this value by the other value. */
130. @SinceKotlin("1.1")
131. public operator fun rem(other: Float): Float
132. /** Calculates the remainder of dividing this value by the other value. */
133. @SinceKotlin("1.1")
134. public operator fun rem(other: Double): Double
136. /** Increments this value. */
137. public operator fun inc(): Int
138. /** Decrements this value. */
139. public operator fun dec(): Int
140. /** Returns this value. */
141. public operator fun unaryPlus(): Int
142. /** Returns the negative of this value. */
143. public operator fun unaryMinus(): Int
145. /** Creates a range from this value to the specified [other] value. */
146. public operator fun rangeTo(other: Byte): IntRange
147. /** Creates a range from this value to the specified [other] value. */
148. public operator fun rangeTo(other: Short): IntRange
149. /** Creates a range from this value to the specified [other] value. */
150. public operator fun rangeTo(other: Int): IntRange
151. /** Creates a range from this value to the specified [other] value. */
152. public operator fun rangeTo(other: Long): LongRange
154. /** Shifts this value left by [bits]. */
155. public infix fun shl(bitCount: Int): Int
156. /** Shifts this value right by [bits], filling the leftmost bits with copies of the sign bit. */
157. public infix fun shr(bitCount: Int): Int
158. /** Shifts this value right by [bits], filling the leftmost bits with zeros. */
159. public infix fun ushr(bitCount: Int): Int
160. /** Performs a bitwise AND operation between the two values. */
161. public infix fun and(other: Int): Int
162. /** Performs a bitwise OR operation between the two values. */
163. public infix fun or(other: Int): Int
164. /** Performs a bitwise XOR operation between the two values. */
165. public infix fun xor(other: Int): Int
166. /** Inverts the bits in this value. */
167. public fun inv(): Int
169. public override fun toByte(): Byte
170. public override fun toChar(): Char
171. public override fun toShort(): Short
172. public override fun toInt(): Int
173. public override fun toLong(): Long
174. public override fun toFloat(): Float
175. public override fun toDouble(): Double
176. }
从源代码我们可以看出,重载操作符的函数需要用 operator 修饰符标记。中缀操作符的函数使用infix修饰符标记。
3.7.5 一元操作符(unary operation)
前缀操作符
| 表达式 | 翻译为 |
|---|---|
+a |
a.unaryPlus() |
-a |
a.unaryMinus() |
!a |
a.not() |
例如,当编译器处理表达式 +a 时,它将执行以下步骤:
- 确定
a的类型,令其为T。 - 为接收者
T查找一个带有operator修饰符的无参函数unaryPlus(),即成员函数或扩展函数。 - 如果函数不存在或不明确,则导致编译错误。
- 如果函数存在且其返回类型为
R,那就表达式+a具有类型R。
编译器对这些操作以及所有其他操作都针对基本类型做了优化,不会引入函数调用的开销。
以下是如何重载一元减运算符的示例:
1. package com.easy.kotlin
3. class OperatorDemo {
5. }
7. data class Point(val x: Int, val y: Int)
9. operator fun Point.unaryMinus() = Point(-x, -y)
测试代码:
1. package com.easy.kotlin
3. import org.junit.Test
4. import org.junit.runner.RunWith
5. import org.junit.runners.JUnit4
7. @RunWith(JUnit4::class)
8. class OperatorDemoTest {
10. @Test
11. fun testPointUnaryMinus() {
12. val p = Point(1, 1)
13. val np = -p
14. println(np) //Point(x=-1, y=-1)
15. }
16. }
递增和递减
| 表达式 | 翻译为 |
|---|---|
a++ |
a.inc() 返回值是a |
a-- |
a.dec() 返回值是a |
++a |
a.inc() 返回值是a+1 |
--a |
a.dec() 返回值是a-1 |
inc() 和 dec() 函数必须返回一个值,它用于赋值给使用
++ 或 -- 操作的变量。
编译器执行以下步骤来解析后缀形式的操作符,例如 a++:
- 确定
a的类型,令其为T。 - 查找一个适用于类型为
T的接收者的、带有operator修饰符的无参数函数inc()。 - 检查函数的返回类型是
T的子类型。
计算表达式的步骤是:
- 把
a的初始值存储到临时存储a_中 - 把
a.inc()结果赋值给a - 把
a_作为表达式的结果返回
( a-- 同理分析)。
对于前缀形式 ++a 和 --a 解析步骤类似,但是返回值是取的新值来返回:
- 把
a.inc()结果赋值给a - 把
a的新值a+1作为表达式结果返回
( --a 同理分析)。
3.7.6 二元操作符
算术运算符
| 表达式 | 翻译为 |
|---|---|
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) |
a..b |
a.rangeTo(b) |
代码示例
1. >>> val a=10
2. >>> val b=3
3. >>> a+b
4. 13
5. >>> a-b
6. 7
7. >>> a/b
8. 3
9. >>> a%b
10. 1
11. >>> a..b
12. 10..3
13. >>> b..a
14. 3..10
字符串的+运算符重载
先用代码举个例子:
1. >>> ""+1
2. 1
3. >>> 1+""
4. error: none of the following functions can be called with the arguments supplied:
5. public final operator fun plus(other: Byte): Int defined in kotlin.Int
6. public final operator fun plus(other: Double): Double defined in kotlin.Int
7. public final operator fun plus(other: Float): Float defined in kotlin.Int
8. public final operator fun plus(other: Int): Int defined in kotlin.Int
9. public final operator fun plus(other: Long): Long defined in kotlin.Int
10. public final operator fun plus(other: Short): Int defined in kotlin.Int
11. 1+""
12. ^
从上面的示例,我们可以看出,在Kotlin中1+""是不允许的(这地方,相比Scala,写这样的Kotlin代码就显得不大友好),只能显式调用toString来相加:
1. >>> 1.toString()+""
2. 1
自定义重载的 + 运算符
下面我们使用一个计数类 Counter 重载的 + 运算符来增加index的计数值。
代码示例
1. data class Counter(var index: Int)
3. operator fun Counter.plus(increment: Int): Counter {
4. return Counter(index + increment)
5. }
测试类
1. package com.easy.kotlin
3. import org.junit.Test
4. import org.junit.runner.RunWith
5. import org.junit.runners.JUnit4
7. @RunWith(JUnit4::class)
8. class OperatorDemoTest
9. @Test
10. fun testCounterIndexPlus() {
11. val c = Counter(1)
12. val cplus = c + 10
13. println(cplus) //Counter(index=11)
14. }
15. }
in 操作符
| 表达式 | 翻译为 |
|---|---|
a in b |
b.contains(a) |
a !in b |
!b.contains(a) |
索引访问操作符
| 表达式 | 翻译为 |
|---|---|
a[i] |
a.get(i) |
a[i] = b |
a.set(i, b) |
方括号转换为调用带有适当数量参数的 get 和 set。
调用操作符
| 表达式 | 翻译为 |
|---|---|
a() |
a.invoke() |
a(i) |
a.invoke(i) |
圆括号转换为调用带有适当数量参数的 invoke。
计算并赋值
| 表达式 | 翻译为 |
|---|---|
a += b |
a.plusAssign(b) |
a -= b |
a.minusAssign(b) |
a *= b |
a.timesAssign(b) |
a /= b |
a.divAssign(b) |
a %= b |
a.modAssign(b) |
对于赋值操作,例如 a += b,编译器会试着生成 a = a + b 的代码(这里包含类型检查:a + b 的类型必须是 a 的子类型)。
相等与不等操作符
Kotlin 中有两种类型的相等性:
- 引用相等
===!==(两个引用指向同一对象) - 结构相等
==!=( 使用equals()判断)
| 表达式 | 翻译为 |
|---|---|
a == b |
a?.equals(b) ?: (b === null) |
a != b |
!(a?.equals(b) ?: (b === null)) |
这个 == 操作符有些特殊:它被翻译成一个复杂的表达式,用于筛选 null 值。
意思是:如果 a 不是 null 则调用 equals(Any?) 函数并返回其值;否则(即 a === null)就计算 b === null 的值并返回。
当与 null 显式比较时,a == null 会被自动转换为 a=== null
注意:=== 和 !==不可重载。
Elvis 操作符 ?:
在Kotin中,Elvis操作符特定是跟null比较。也就是说
1. y = x?:0
等价于
1. val y = if(x!==null) x else 0
主要用来作null安全性检查。
Elvis操作符 ?: 是一个二元运算符,如果第一个操作数为真,则返回第一个操作数,否则将计算并返回其第二个操作数。它是三元条件运算符的变体。命名灵感来自猫王的发型风格。
Kotlin中没有这样的三元运算符 true?1:0,取而代之的是if(true) 1 else 0。而Elvis操作符算是精简版的三元运算符。
我们在Java中使用的三元运算符的语法,你通常要重复变量两次, 示例:
1. String name = "Elvis Presley";
2. String displayName = (name != null) ? name : "Unknown";
取而代之,你可以使用Elvis操作符。
1. String name = "Elvis Presley";
2. String displayName = name?:"Unknown"
我们可以看出,用Elvis操作符(?:)可以把带有默认值的if/else结构写的及其短小。用Elvis操作符不用检查null(避免了NullPointerException),也不用重复变量。
这个Elvis操作符功能在Spring 表达式语言 (SpEL)中提供。
在Kotlin中当然就没有理由不支持这个特性。
代码示例:
1. >>> val x = null
2. >>> val y = x?:0
3. >>> y
4. 0
5. >>> val x = false
6. >>> val y = x?:0
7. >>> y
8. false
9. >>> val x = ""
10. >>> val y = x?:0
11. >>> y
13. >>> val x = "abc"
14. >>> val y = x?:0
15. >>> y
16. abc
比较操作符
| 表达式 | 翻译为 |
|---|---|
a > b |
a.compareTo(b) > 0 |
a < b |
a.compareTo(b) < 0 |
a >= b |
a.compareTo(b) >= 0 |
a <= b |
a.compareTo(b) <= 0 |
所有的比较都转换为对 compareTo 的调用,这个函数需要返回 Int 值
用infix函数自定义中缀操作符
我们可以通过自定义infix函数来实现中缀操作符。
代码示例
1. data class Person(val name: String, val age: Int)
3. infix fun Person.grow(years: Int): Person {
4. return Person(name, age + years)
5. }
测试代码
1. package com.easy.kotlin
3. import org.junit.Test
4. import org.junit.runner.RunWith
5. import org.junit.runners.JUnit4
7. @RunWith(JUnit4::class)
8. class InfixFunctionDemoTest {
10. @Test fun testInfixFuntion() {
11. val person = Person("Jack", 20)
13. println(person.grow(2))
15. println(person grow 2)
16. }
17. }
输出
1. Person(name=Jack, age=22)
2. Person(name=Jack, age=22)
