3.7 语法与标识符

我们知道,任何一门编程语言都会有一些自己专用的关键字、符号以及规定的语法规则等等。程序员们使用这些基础词汇和语法规则来表达算法步骤,也就是写代码的过程。

词法分析是编译器对源码进行编译的基础步骤之一。词法分析是将源程序读入的字符序列,按照一定的规则转换成词法单元(Token)序列的过程。词法单元是语言中具有独立意义的最小单元,包括修饰符、关键字、常数、运算符、边界符等等。

3.7.1 修饰符

在Kotlin源码工程中的kotlin/grammar/src/modifiers.grm文件中,描述了Kotlin语言的修饰符,我们在此作简要注释说明:

  1. /**
  2. ## Modifiers
  3. */
  4. modifiers
  5. : (modifier | annotations)*
  6. ;
  7. typeModifiers
  8. : (suspendModifier | annotations)*
  9. ;
  10. modifier
  11. : classModifier
  12. : accessModifier
  13. : varianceAnnotation
  14. : memberModifier
  15. : parameterModifier
  16. : typeParameterModifier
  17. : functionModifier
  18. : propertyModifier
  19. ;
  20. classModifier 类修饰符
  21. : "abstract" 抽象类
  22. : "final" 不可被继承final
  23. : "enum" 枚举类
  24. : "open" 可继承open
  25. : "annotation" 注解类
  26. : "sealed" 密封类
  27. : "data" 数据类
  28. ;
  29. memberModifier
  30. : "override" 重写函数
  31. : "open" 可被重写
  32. : "final" 不可被重写
  33. : "abstract" 抽象函数
  34. : "lateinit" 后期初始化
  35. ;
  36. accessModifier 访问权限控制, 默认是public
  37. : "private"
  38. : "protected"
  39. : "public"
  40. : "internal" 整个模块内(模块(module)是指一起编译的一组 Kotlin 源代码文件: 例如,一个 IntelliJ IDEA 模块,一个 Maven 工程, Gradle 工程,通过 Ant 任务的一次调用编译的一组文件等)可访问
  41. ;
  42. varianceAnnotation 泛型可变性
  43. : "in"
  44. : "out"
  45. ;
  46. parameterModifier
  47. : "noinline"
  48. : "crossinline"
  49. : "vararg" 变长参数
  50. ;
  51. typeParameterModifier
  52. : "reified"
  53. ;
  54. functionModifier
  55. : "tailrec" 尾递归
  56. : "operator"
  57. : "infix"
  58. : "inline"
  59. : "external"
  60. : suspendModifier
  61. ;
  62. propertyModifier
  63. : "const"
  64. ;
  65. suspendModifier
  66. : "suspend"
  67. ;

这些修饰符的完整定义,在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. };
  9. TokenSet MODIFIER_KEYWORDS = TokenSet.create(MODIFIER_KEYWORDS_ARRAY);
  10. TokenSet TYPE_MODIFIER_KEYWORDS = TokenSet.create(SUSPEND_KEYWORD);
  11. TokenSet TYPE_ARGUMENT_MODIFIER_KEYWORDS = TokenSet.create(IN_KEYWORD, OUT_KEYWORD);
  12. TokenSet RESERVED_VALUE_PARAMETER_MODIFIER_KEYWORDS = TokenSet.create(OUT_KEYWORD, VARARG_KEYWORD);
  13. 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. );
  10. TokenSet SOFT_KEYWORDS = TokenSet.create(FILE_KEYWORD, IMPORT_KEYWORD, WHERE_KEYWORD, BY_KEYWORD, GET_KEYWORD,
  11. SET_KEYWORD, ABSTRACT_KEYWORD, ENUM_KEYWORD, OPEN_KEYWORD, INNER_KEYWORD,
  12. OVERRIDE_KEYWORD, PRIVATE_KEYWORD, PUBLIC_KEYWORD, INTERNAL_KEYWORD, PROTECTED_KEYWORD,
  13. CATCH_KEYWORD, FINALLY_KEYWORD, OUT_KEYWORD, FINAL_KEYWORD, VARARG_KEYWORD, REIFIED_KEYWORD,
  14. DYNAMIC_KEYWORD, COMPANION_KEYWORD, CONSTRUCTOR_KEYWORD, INIT_KEYWORD, SEALED_KEYWORD,
  15. FIELD_KEYWORD, PROPERTY_KEYWORD, RECEIVER_KEYWORD, PARAM_KEYWORD, SETPARAM_KEYWORD,
  16. DELEGATE_KEYWORD,
  17. LATEINIT_KEYWORD,
  18. DATA_KEYWORD, INLINE_KEYWORD, NOINLINE_KEYWORD, TAILREC_KEYWORD, EXTERNAL_KEYWORD,
  19. ANNOTATION_KEYWORD, CROSSINLINE_KEYWORD, CONST_KEYWORD, OPERATOR_KEYWORD, INFIX_KEYWORD,
  20. SUSPEND_KEYWORD, HEADER_KEYWORD, IMPL_KEYWORD
  21. );

其中,对应的关键字如下:

  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");
  28. // Reserved for future use:
  29. KtKeywordToken TYPEOF_KEYWORD = KtKeywordToken.keyword("typeof");
  30. ...
  31. KtKeywordToken FILE_KEYWORD = KtKeywordToken.softKeyword("file");
  32. KtKeywordToken FIELD_KEYWORD = KtKeywordToken.softKeyword("field");
  33. KtKeywordToken PROPERTY_KEYWORD = KtKeywordToken.softKeyword("property");
  34. KtKeywordToken RECEIVER_KEYWORD = KtKeywordToken.softKeyword("receiver");
  35. KtKeywordToken PARAM_KEYWORD = KtKeywordToken.softKeyword("param");
  36. KtKeywordToken SETPARAM_KEYWORD = KtKeywordToken.softKeyword("setparam");
  37. KtKeywordToken DELEGATE_KEYWORD = KtKeywordToken.softKeyword("delegate");
  38. KtKeywordToken IMPORT_KEYWORD = KtKeywordToken.softKeyword("import");
  39. KtKeywordToken WHERE_KEYWORD = KtKeywordToken.softKeyword("where");
  40. KtKeywordToken BY_KEYWORD = KtKeywordToken.softKeyword("by");
  41. KtKeywordToken GET_KEYWORD = KtKeywordToken.softKeyword("get");
  42. KtKeywordToken SET_KEYWORD = KtKeywordToken.softKeyword("set");
  43. KtKeywordToken CONSTRUCTOR_KEYWORD = KtKeywordToken.softKeyword("constructor");
  44. KtKeywordToken INIT_KEYWORD = KtKeywordToken.softKeyword("init");
  45. KtModifierKeywordToken ABSTRACT_KEYWORD = KtModifierKeywordToken.softKeywordModifier("abstract");
  46. KtModifierKeywordToken ENUM_KEYWORD = KtModifierKeywordToken.softKeywordModifier("enum");
  47. KtModifierKeywordToken OPEN_KEYWORD = KtModifierKeywordToken.softKeywordModifier("open");
  48. KtModifierKeywordToken INNER_KEYWORD = KtModifierKeywordToken.softKeywordModifier("inner");
  49. KtModifierKeywordToken OVERRIDE_KEYWORD = KtModifierKeywordToken.softKeywordModifier("override");
  50. KtModifierKeywordToken PRIVATE_KEYWORD = KtModifierKeywordToken.softKeywordModifier("private");
  51. KtModifierKeywordToken PUBLIC_KEYWORD = KtModifierKeywordToken.softKeywordModifier("public");
  52. KtModifierKeywordToken INTERNAL_KEYWORD = KtModifierKeywordToken.softKeywordModifier("internal");
  53. KtModifierKeywordToken PROTECTED_KEYWORD = KtModifierKeywordToken.softKeywordModifier("protected");
  54. KtKeywordToken CATCH_KEYWORD = KtKeywordToken.softKeyword("catch");
  55. KtModifierKeywordToken OUT_KEYWORD = KtModifierKeywordToken.softKeywordModifier("out");
  56. KtModifierKeywordToken VARARG_KEYWORD = KtModifierKeywordToken.softKeywordModifier("vararg");
  57. KtModifierKeywordToken REIFIED_KEYWORD = KtModifierKeywordToken.softKeywordModifier("reified");
  58. KtKeywordToken DYNAMIC_KEYWORD = KtKeywordToken.softKeyword("dynamic");
  59. KtModifierKeywordToken COMPANION_KEYWORD = KtModifierKeywordToken.softKeywordModifier("companion");
  60. KtModifierKeywordToken SEALED_KEYWORD = KtModifierKeywordToken.softKeywordModifier("sealed");
  61. KtModifierKeywordToken DEFAULT_VISIBILITY_KEYWORD = PUBLIC_KEYWORD;
  62. KtKeywordToken FINALLY_KEYWORD = KtKeywordToken.softKeyword("finally");
  63. KtModifierKeywordToken FINAL_KEYWORD = KtModifierKeywordToken.softKeywordModifier("final");
  64. KtModifierKeywordToken LATEINIT_KEYWORD = KtModifierKeywordToken.softKeywordModifier("lateinit");
  65. KtModifierKeywordToken DATA_KEYWORD = KtModifierKeywordToken.softKeywordModifier("data");
  66. KtModifierKeywordToken INLINE_KEYWORD = KtModifierKeywordToken.softKeywordModifier("inline");
  67. KtModifierKeywordToken NOINLINE_KEYWORD = KtModifierKeywordToken.softKeywordModifier("noinline");
  68. KtModifierKeywordToken TAILREC_KEYWORD = KtModifierKeywordToken.softKeywordModifier("tailrec");
  69. KtModifierKeywordToken EXTERNAL_KEYWORD = KtModifierKeywordToken.softKeywordModifier("external");
  70. KtModifierKeywordToken ANNOTATION_KEYWORD = KtModifierKeywordToken.softKeywordModifier("annotation");
  71. KtModifierKeywordToken CROSSINLINE_KEYWORD = KtModifierKeywordToken.softKeywordModifier("crossinline");
  72. KtModifierKeywordToken OPERATOR_KEYWORD = KtModifierKeywordToken.softKeywordModifier("operator");
  73. KtModifierKeywordToken INFIX_KEYWORD = KtModifierKeywordToken.softKeywordModifier("infix");
  74. KtModifierKeywordToken CONST_KEYWORD = KtModifierKeywordToken.softKeywordModifier("const");
  75. KtModifierKeywordToken SUSPEND_KEYWORD = KtModifierKeywordToken.softKeywordModifier("suspend");
  76. KtModifierKeywordToken HEADER_KEYWORD = KtModifierKeywordToken.softKeywordModifier("header");
  77. KtModifierKeywordToken IMPL_KEYWORD = KtModifierKeywordToken.softKeywordModifier("impl");

this 关键字

this关键字持有当前对象的引用。我们可以使用this来引用变量或者成员函数,也可以使用return this,来返回某个类的引用。

代码示例

  1. class ThisDemo {
  2. val thisis = "THIS IS"
  3. fun whatIsThis(): ThisDemo {
  4. println(this.thisis) //引用变量
  5. this.howIsThis()// 引用成员函数
  6. return this // 返回此类的引用
  7. }
  8. fun howIsThis(){
  9. println("HOW IS THIS ?")
  10. }
  11. }

测试代码

  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!"
  3. inner class Inner {
  4. fun m() {
  5. val outer = this@Outer
  6. val inner = this@Inner
  7. val pthis = this
  8. println("outer=" + outer)
  9. println("inner=" + inner)
  10. println("pthis=" + pthis)
  11. println(this@Outer.oh)
  12. val fun1 = hello@ fun String.() {
  13. val d1 = this // fun1 的接收者
  14. println("d1" + d1)
  15. }
  16. val fun2 = { s: String ->
  17. val d2 = this
  18. println("d2=" + d2)
  19. }
  20. "abc".fun1()
  21. fun2
  22. }
  23. }
  24. }

测试代码:

  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"
  4. fun ff() {
  5. println("FFF")
  6. }
  7. }
  8. class Son : Father {
  9. override var firstName = super.firstName
  10. override var lastName = "Jack"
  11. constructor(lastName: String) {
  12. this.lastName = lastName
  13. }
  14. fun love() {
  15. super.ff() // 调用父类方法
  16. println(super.firstName + " " + super.lastName + " Love " + this.firstName + " " + this.lastName)
  17. }
  18. }

测试代码

  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", "@");
  47. 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. ...
  3. /**
  4. * Compares this value with the specified value for order.
  5. * Returns zero if this value is equal to the specified other value, a negative number if it's less than other,
  6. * or a positive number if it's greater than other.
  7. */
  8. public operator fun compareTo(other: Byte): Int
  9. /**
  10. * Compares this value with the specified value for order.
  11. * Returns zero if this value is equal to the specified other value, a negative number if it's less than other,
  12. * or a positive number if it's greater than other.
  13. */
  14. public operator fun compareTo(other: Short): Int
  15. /**
  16. * Compares this value with the specified value for order.
  17. * Returns zero if this value is equal to the specified other value, a negative number if it's less than other,
  18. * or a positive number if it's greater than other.
  19. */
  20. public override operator fun compareTo(other: Int): Int
  21. /**
  22. * Compares this value with the specified value for order.
  23. * Returns zero if this value is equal to the specified other value, a negative number if it's less than other,
  24. * or a positive number if it's greater than other.
  25. */
  26. public operator fun compareTo(other: Long): Int
  27. /**
  28. * Compares this value with the specified value for order.
  29. * Returns zero if this value is equal to the specified other value, a negative number if it's less than other,
  30. * or a positive number if it's greater than other.
  31. */
  32. public operator fun compareTo(other: Float): Int
  33. /**
  34. * Compares this value with the specified value for order.
  35. * Returns zero if this value is equal to the specified other value, a negative number if it's less than other,
  36. * or a positive number if it's greater than other.
  37. */
  38. public operator fun compareTo(other: Double): Int
  39. /** Adds the other value to this value. */
  40. public operator fun plus(other: Byte): Int
  41. /** Adds the other value to this value. */
  42. public operator fun plus(other: Short): Int
  43. /** Adds the other value to this value. */
  44. public operator fun plus(other: Int): Int
  45. /** Adds the other value to this value. */
  46. public operator fun plus(other: Long): Long
  47. /** Adds the other value to this value. */
  48. public operator fun plus(other: Float): Float
  49. /** Adds the other value to this value. */
  50. public operator fun plus(other: Double): Double
  51. /** Subtracts the other value from this value. */
  52. public operator fun minus(other: Byte): Int
  53. /** Subtracts the other value from this value. */
  54. public operator fun minus(other: Short): Int
  55. /** Subtracts the other value from this value. */
  56. public operator fun minus(other: Int): Int
  57. /** Subtracts the other value from this value. */
  58. public operator fun minus(other: Long): Long
  59. /** Subtracts the other value from this value. */
  60. public operator fun minus(other: Float): Float
  61. /** Subtracts the other value from this value. */
  62. public operator fun minus(other: Double): Double
  63. /** Multiplies this value by the other value. */
  64. public operator fun times(other: Byte): Int
  65. /** Multiplies this value by the other value. */
  66. public operator fun times(other: Short): Int
  67. /** Multiplies this value by the other value. */
  68. public operator fun times(other: Int): Int
  69. /** Multiplies this value by the other value. */
  70. public operator fun times(other: Long): Long
  71. /** Multiplies this value by the other value. */
  72. public operator fun times(other: Float): Float
  73. /** Multiplies this value by the other value. */
  74. public operator fun times(other: Double): Double
  75. /** Divides this value by the other value. */
  76. public operator fun div(other: Byte): Int
  77. /** Divides this value by the other value. */
  78. public operator fun div(other: Short): Int
  79. /** Divides this value by the other value. */
  80. public operator fun div(other: Int): Int
  81. /** Divides this value by the other value. */
  82. public operator fun div(other: Long): Long
  83. /** Divides this value by the other value. */
  84. public operator fun div(other: Float): Float
  85. /** Divides this value by the other value. */
  86. public operator fun div(other: Double): Double
  87. /** Calculates the remainder of dividing this value by the other value. */
  88. @Deprecated("Use rem(other) instead", ReplaceWith("rem(other)"), DeprecationLevel.WARNING)
  89. public operator fun mod(other: Byte): Int
  90. /** Calculates the remainder of dividing this value by the other value. */
  91. @Deprecated("Use rem(other) instead", ReplaceWith("rem(other)"), DeprecationLevel.WARNING)
  92. public operator fun mod(other: Short): Int
  93. /** Calculates the remainder of dividing this value by the other value. */
  94. @Deprecated("Use rem(other) instead", ReplaceWith("rem(other)"), DeprecationLevel.WARNING)
  95. public operator fun mod(other: Int): Int
  96. /** Calculates the remainder of dividing this value by the other value. */
  97. @Deprecated("Use rem(other) instead", ReplaceWith("rem(other)"), DeprecationLevel.WARNING)
  98. public operator fun mod(other: Long): Long
  99. /** Calculates the remainder of dividing this value by the other value. */
  100. @Deprecated("Use rem(other) instead", ReplaceWith("rem(other)"), DeprecationLevel.WARNING)
  101. public operator fun mod(other: Float): Float
  102. /** Calculates the remainder of dividing this value by the other value. */
  103. @Deprecated("Use rem(other) instead", ReplaceWith("rem(other)"), DeprecationLevel.WARNING)
  104. public operator fun mod(other: Double): Double
  105. /** Calculates the remainder of dividing this value by the other value. */
  106. @SinceKotlin("1.1")
  107. public operator fun rem(other: Byte): Int
  108. /** Calculates the remainder of dividing this value by the other value. */
  109. @SinceKotlin("1.1")
  110. public operator fun rem(other: Short): Int
  111. /** Calculates the remainder of dividing this value by the other value. */
  112. @SinceKotlin("1.1")
  113. public operator fun rem(other: Int): Int
  114. /** Calculates the remainder of dividing this value by the other value. */
  115. @SinceKotlin("1.1")
  116. public operator fun rem(other: Long): Long
  117. /** Calculates the remainder of dividing this value by the other value. */
  118. @SinceKotlin("1.1")
  119. public operator fun rem(other: Float): Float
  120. /** Calculates the remainder of dividing this value by the other value. */
  121. @SinceKotlin("1.1")
  122. public operator fun rem(other: Double): Double
  123. /** Increments this value. */
  124. public operator fun inc(): Int
  125. /** Decrements this value. */
  126. public operator fun dec(): Int
  127. /** Returns this value. */
  128. public operator fun unaryPlus(): Int
  129. /** Returns the negative of this value. */
  130. public operator fun unaryMinus(): Int
  131. /** Creates a range from this value to the specified [other] value. */
  132. public operator fun rangeTo(other: Byte): IntRange
  133. /** Creates a range from this value to the specified [other] value. */
  134. public operator fun rangeTo(other: Short): IntRange
  135. /** Creates a range from this value to the specified [other] value. */
  136. public operator fun rangeTo(other: Int): IntRange
  137. /** Creates a range from this value to the specified [other] value. */
  138. public operator fun rangeTo(other: Long): LongRange
  139. /** Shifts this value left by [bits]. */
  140. public infix fun shl(bitCount: Int): Int
  141. /** Shifts this value right by [bits], filling the leftmost bits with copies of the sign bit. */
  142. public infix fun shr(bitCount: Int): Int
  143. /** Shifts this value right by [bits], filling the leftmost bits with zeros. */
  144. public infix fun ushr(bitCount: Int): Int
  145. /** Performs a bitwise AND operation between the two values. */
  146. public infix fun and(other: Int): Int
  147. /** Performs a bitwise OR operation between the two values. */
  148. public infix fun or(other: Int): Int
  149. /** Performs a bitwise XOR operation between the two values. */
  150. public infix fun xor(other: Int): Int
  151. /** Inverts the bits in this value. */
  152. public fun inv(): Int
  153. public override fun toByte(): Byte
  154. public override fun toChar(): Char
  155. public override fun toShort(): Short
  156. public override fun toInt(): Int
  157. public override fun toLong(): Long
  158. public override fun toFloat(): Float
  159. public override fun toDouble(): Double
  160. }

从源代码我们可以看出,重载操作符的函数需要用 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
  2. class OperatorDemo {
  3. }
  4. data class Point(val x: Int, val y: Int)
  5. operator fun Point.unaryMinus() = Point(-x, -y)

测试代码:

  1. package com.easy.kotlin
  2. import org.junit.Test
  3. import org.junit.runner.RunWith
  4. import org.junit.runners.JUnit4
  5. @RunWith(JUnit4::class)
  6. class OperatorDemoTest {
  7. @Test
  8. fun testPointUnaryMinus() {
  9. val p = Point(1, 1)
  10. val np = -p
  11. println(np) //Point(x=-1, y=-1)
  12. }
  13. }

递增和递减

表达式 翻译为
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)
  2. operator fun Counter.plus(increment: Int): Counter {
  3. return Counter(index + increment)
  4. }

测试类

  1. package com.easy.kotlin
  2. import org.junit.Test
  3. import org.junit.runner.RunWith
  4. import org.junit.runners.JUnit4
  5. @RunWith(JUnit4::class)
  6. class OperatorDemoTest
  7. @Test
  8. fun testCounterIndexPlus() {
  9. val c = Counter(1)
  10. val cplus = c + 10
  11. println(cplus) //Counter(index=11)
  12. }
  13. }

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)

方括号转换为调用带有适当数量参数的 getset

调用操作符

表达式 翻译为
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
  12. >>> val x = "abc"
  13. >>> val y = x?:0
  14. >>> y
  15. 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)
  2. infix fun Person.grow(years: Int): Person {
  3. return Person(name, age + years)
  4. }

测试代码

  1. package com.easy.kotlin
  2. import org.junit.Test
  3. import org.junit.runner.RunWith
  4. import org.junit.runners.JUnit4
  5. @RunWith(JUnit4::class)
  6. class InfixFunctionDemoTest {
  7. @Test fun testInfixFuntion() {
  8. val person = Person("Jack", 20)
  9. println(person.grow(2))
  10. println(person grow 2)
  11. }
  12. }

输出

  1. Person(name=Jack, age=22)
  2. Person(name=Jack, age=22)