Kotlin 简明教程
Kotlin - Keywords
Kotlin 关键字是 Kotlin 编程中使用的预定义保留字,对编译器具有特殊含义。这些字不能用作标识符(变量名、包名、函数名等),如果使用,编译器将引发异常。
Kotlin keywords are predefined, reserved words used in Kotlin programming that have special meanings to the compiler. These words cannot be used as an identifier (variables names, package names, function names etc.) and if used then compiler will raise an exception.
Kotlin 使用 fun 关键字来定义函数,因此,如果我们尝试将其用作变量名,则将是一个异常。例如:
Kotlin uses fun keyword to define a function, so if we we will try to use it as a variable name then it will be an exception. For example:
fun main() {
var fun = "Zara Ali" // Not allowed, throws an exception
var age = 19 // Valid variable name
println("Name = $fun")
println("Age = $age")
}
当你运行上述 Kotlin 程序时,它将生成以下输出:
When you run the above Kotlin program, it will generate the following output:
main.kt:2:7: error: expecting property name or receiver type
var fun = "Zara Ali" // Not allowed, throws an exception
^
main.kt:2:11: error: expecting '('
var fun = "Zara Ali" // Not allowed, throws an exception
^
main.kt:5:21: error: keyword cannot be used as a reference
println("Name = $fun")
^
Kotlin 关键字已分为三大类:(a) 硬关键字 (b) 软关键字 (c) 修饰符关键字
Kotlin keywords have been categorised into three broad categories: (a) Hard Keywords (b) Soft Keywords (c) Modifier Keywords
作为一个良好的编程实践,强烈建议在 Kotlin 中编码时不使用任何提到的关键字来命名任何标识符。
As a good programming practice, it is highly recommended not to use any of the mentioned keywords to name any identifiers while coding in Kotlin.
(a) Kotlin Hard Keywords
以下是硬关键字的列表,它们不能用作标识符:
Following is a list of hard keywords and they cannot be used as identifiers:
as |
as? |
break |
class |
continue |
do |
else |
false |
for |
fun |
if |
in |
!in |
interface |
is |
!is |
null |
object |
package |
return |
super |
this |
throw |
true |
try |
typealias |
typeof |
val |
var |
when |
while |
(b) Kotlin Soft Keywords
以下是关键字(软)清单,适用于特定环境时,并且可以在其他环境中用作标识符:
Following is the list of keywords (soft) in the context when they are applicable and can be used as identifiers in other contexts:
by |
catch |
constructor |
delegate |
dynamic |
field |
file |
finally |
get |
import |
init |
param |
property |
receiver |
set |
setparam |
value |
where |
(c) Kotlin Modifier Keywords
以下是标记清单,这些标记用作声明的修饰符列表中的关键字,并且可以在其他环境中用作标识符:
Following is the list of tokens which act as keywords in modifier lists of declarations and can be used as identifiers in other contexts:
actual |
abstract |
annotation |
companion |
const |
crossinline |
data |
enum |
expect |
external |
final |
infix |
inline |
inner |
internal |
lateinit |
noinline |
open |
operator |
out |
override |
private |
protected |
public |
reified |
sealed |
suspend |
tailrec |
vararg |