Kotlin 有一个标准库, 提供了必要的类型, 函数, 集合, 以及实用工具, 让你的代码更加简洁, 而且富有表现力. 在任何 Kotlin 文件中可以使用标准库 (everything in the kotlin 包) 的大部分内容, 不需要明确的导入:
fun main() {
val text = "emosewa si niltoK"
// 使用标准库的 reversed() 函数
val reversedText = text.reversed()
// 使用标准库的 print() 函数
print(reversedText)
// 输出结果为: Kotlin is awesome
}
import kotlinx.datetime.*
fun main() {
val now = Clock.System.now() // 得到当前时刻
println("Current instant: $now")
val zone = TimeZone.of("America/New_York")
val localDateTime = now.toLocalDateTime(zone)
println("Local date-time in NY: $localDateTime")
}
在这个示例中:
导入 kotlinx.datetime 包.
使用 Clock.System.now() 函数, 创建 Instant 类的一个实例, 其中包含当前时间, 并将结果赋值给 now 变量.
打印输出当前时间.
使用 TimeZone.of() 函数, 找到纽约的时区, 并将结果赋值给 zone 变量.
在包含当前时间的实例上调用 .toLocalDateTime() 函数, 使用纽约的时区作为参数.
将结果赋值给 localDateTime 变量.
打印输出针对纽约的时区调整后的时间.
对 API 选择使用者同意(Opt-in)
库的作者可能会对某些 API 标记为, 在你的代码中使用之前, 需要使用者同意(Opt-in). 当 API 还处于开发阶段, 未来可能发生变化时, 通常会这样做. 如果你不进行用者同意(Opt-in), 你会看到类似这样的警告或错误信息:
This declaration needs opt-in. Its usage should be marked with '@...' or '@OptIn(...)'
// 请在这里编写你的代码
fun calculateCompoundInterest(P: Double, r: Double, n: Int, t: Int): Double {
// 请在这里编写你的代码
}
fun main() {
val principal = 1000.0
val rate = 0.05
val timesCompounded = 4
val years = 5
val amount = calculateCompoundInterest(principal, rate, timesCompounded, years)
println("The accumulated amount is: $amount")
// 输出结果为: The accumulated amount is: 1282.0372317085844
}
import kotlin.math.*
fun calculateCompoundInterest(P: Double, r: Double, n: Int, t: Int): Double {
return P * (1 + r / n).pow(n * t)
}
fun main() {
val principal = 1000.0
val rate = 0.05
val timesCompounded = 4
val years = 5
val amount = calculateCompoundInterest(principal, rate, timesCompounded, years)
println("The accumulated amount is: $amount")
// 输出结果为: The accumulated amount is: 1282.0372317085844
}