Hello world
这是一个打印“Hello, world!”的简单程序:
kotlin
fun main() {
println("Hello, world!")
// Hello, world!
}
在 Kotlin 中:
函数是执行特定任务的一组指令。创建函数后,你可以随时使用它来执行该任务,而无需重复编写指令。函数将在后面的章节中更详细地讨论。在此之前,所有示例都使用 main()
函数。
变量
所有程序都需要能够存储数据,而变量正是为此而生。在 Kotlin 中,你可以声明:
- 用
val
声明只读变量 - 用
var
声明可变变量
只读变量一旦赋值后,就不能再更改它的值了。
要赋值,请使用赋值操作符 =
。
例如:
kotlin
fun main() {
val popcorn = 5 // There are 5 boxes of popcorn
val hotdog = 7 // There are 7 hotdogs
var customers = 10 // There are 10 customers in the queue
// Some customers leave the queue
customers = 8
println(customers)
// 8
}
变量可以声明在
main()
函数之外,在程序的开头。以这种方式声明的变量被称为顶层声明。
由于 customers
是一个可变变量,它可以在声明后重新赋值。
我们建议默认将所有变量声明为只读 (
val
)。只有在你确实需要时才使用可变变量 (var
)。这样,你就不太可能意外地更改不打算更改的内容。
字符串模板
了解如何将变量内容打印到标准输出会很有用。你可以使用字符串模板来完成此操作。你可以使用模板表达式来访问存储在变量及其他对象中的数据,并将其转换为字符串。字符串值是双引号 ""
中的字符序列。模板表达式总是以美元符号 $
开头。
要在模板表达式中求值一段代码,请在美元符号 $
后面将代码放在花括号 {}
内。
例如:
kotlin
fun main() {
val customers = 10
println("There are $customers customers")
// There are 10 customers
println("There are ${customers + 1} customers")
// There are 11 customers
}
有关更多信息,请参阅 字符串模板。
你会注意到变量没有声明任何类型。Kotlin 已经推断出类型本身是 Int
。本教程将在下一章中解释不同的 Kotlin 基本类型以及如何声明它们。
练习
练习
补全代码,使程序将 "Mary is 20 years old"
打印到标准输出:
kotlin
fun main() {
val name = "Mary"
val age = 20
// Write your code here
}
示例解决方案
kotlin
fun main() {
val name = "Mary"
val age = 20
println("$name is $age years old")
}