3.2.2 基本类型
原文链接: https://kotlinlang.org/docs/kotlin-tour-basic-types.html
3.2.2 基本类型
Kotlin 中的每个变量和数据结构都有类型。类型很重要,因为它们告诉编译器你可以对这个变量或数据结构做什么——换句话说,它有哪些函数和属性。
在上一章中,Kotlin 能够从之前的示例中判断出 customers 的类型是 Int。Kotlin 这种推断类型的能力称为类型推断。customers 被赋予了一个整数值,由此 Kotlin 推断出 customers 具有数值类型 Int。因此,编译器知道你可以在 customers 上做算术运算:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| fun main() {
var customers = 10
// Some customers leave the queue
customers = 8
customers = customers + 3 // Example of addition: 11
customers += 7 // Example of addition: 18
customers -= 3 // Example of subtraction: 15
customers *= 2 // Example of multiplication: 30
customers /= 3 // Example of division: 10
println(customers) // 10
}
|
提示: +=、-=、*=、/= 和 %= 是复合赋值运算符。更多信息请参阅复合赋值。
Kotlin 总共有以下基本类型:
| 类别 | 基本类型 | 示例代码 |
|---|
| 整数 | Byte、Short、Int、Long | val year: Int = 2020 |
val amount: Long = 350_000_000 | | |
| 无符号整数 | UByte、UShort、UInt、ULong | val score: UInt = 100u |
| 浮点数 | Float、Double | val currentTemp: Float = 24.5f |
val price: Double = 19.99 | | |
| 布尔值 | Boolean | val isEnabled: Boolean = true |
| 字符 | Char | val separator: Char = ',' |
| 字符串 | String | val message: String = "Hello, world!" |
关于基本类型及其属性的更多信息,请参阅类型概览。
掌握这些知识之后,你就可以先声明变量、稍后再初始化它们。只要变量在第一次读取之前完成初始化,Kotlin 就能处理好。
要声明一个不初始化的变量,请用 : 指定它的类型。例如:
1
2
3
4
5
6
7
8
9
10
11
12
13
| fun main() {
// Variable declared without initialization
val d: Int
// Variable initialized
d = 3
// Variable explicitly typed and initialized
val e: String = "hello"
// Variables can be read because they have been initialized
println(d) // 3
println(e) // hello
}
|
如果变量在被读取之前没有初始化,就会看到错误:
1
2
3
4
5
6
7
8
| fun main() {
// Variable declared without initialization
val d: Int
// Triggers an error
println(d)
// Variable 'd' must be initialized
}
|
现在你已经知道如何声明基本类型了,接下来该了解集合了。
练习
习题
为每个变量显式声明正确的类型:
1
2
3
4
5
6
7
8
| fun main() {
val a: Int = 1000
val b = "log message"
val c = 3.14
val d = 100_000_000_000_000
val e = false
val f = '\n'
}
|
1
2
3
4
5
6
7
8
| fun main() {
val a: Int = 1000
val b: String = "log message"
val c: Double = 3.14
val d: Long = 100_000_000_000_000
val e: Boolean = false
val f: Char = '\n'
}
|
示例解答
另请参阅
上一步
下一步