已发布·持续改进
Kotlin 指南 · 4/6
本章目前仅提供英文版。
As a program grows, you split it into files and packages and pull in third-party libraries. This chapter covers packages and imports, visibility, adding dependencies with Gradle, and a short look at Kotlin Multiplatform.
The package line at the top of a file sets the namespace for everything in it. Unlike Java, one file may hold several classes, and functions and properties can live at the top level, outside any class.
// src/main/kotlin/com/example/shop/Order.kt
package com.example.shop
data class Order(val id: Long, val amount: Int)
fun totalOf(orders: List<Order>): Int = orders.sumOf { it.amount }
const val FREE_SHIPPING_MIN = 50Kotlin does not require directories to mirror package names, but the official style guide recommends it. A file without a package line belongs to the unnamed default package.
import brings in declarations from other packages: classes, but also top-level functions and properties. Resolve name clashes with an alias via as.
package com.example.app
import com.example.shop.Order
import com.example.shop.totalOf
import com.example.shop.FREE_SHIPPING_MIN
import com.example.legacy.Order as LegacyOrder
import java.time.LocalDate
fun main() {
val orders = listOf(Order(1, 30), Order(2, 42))
val total = totalOf(orders)
println("${LocalDate.now()} total: $total")
println("Free shipping: ${total >= FREE_SHIPPING_MIN}")
}Star imports such as import com.example.shop.* also work. Several packages are imported by default, including kotlin.*, kotlin.collections.*, kotlin.text.*, kotlin.io.* and kotlin.ranges.*, plus java.lang.* on the JVM. That is why listOf and println need no import.
| Modifier | Top-level declaration | Class member |
|---|---|---|
public (default) | visible everywhere | visible everywhere |
internal | same module | same module |
protected | not allowed | class and subclasses |
private | same file | inside the class |
Declarations are public unless you say otherwise. A module is a set of files compiled together, typically one Gradle module (strictly, one of its source sets). When writing a library, mark implementation details so they stay out of the public API.
internalMost Kotlin libraries are published to Maven Central and identified by group:artifact:version coordinates. Current Gradle projects usually keep versions in a version catalog. Replace each x.y.z below with the version you actually want.
# gradle/libs.versions.toml
[versions]
kotlin = "x.y.z"
coroutines = "x.y.z"
[libraries]
kotlinx-coroutines-core = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-core", version.ref = "coroutines" }
[plugins]
kotlin-jvm = { id = "org.jetbrains.kotlin.jvm", version.ref = "kotlin" }// build.gradle.kts
plugins {
alias(libs.plugins.kotlin.jvm)
}
repositories {
mavenCentral()
}
dependencies {
implementation(libs.kotlinx.coroutines.core) // from the catalog
implementation("com.squareup.okhttp3:okhttp:x.y.z") // raw coordinates
testImplementation(kotlin("test"))
}implementation is for dependencies needed to compile and run, testImplementation for test-only ones, and runtimeOnly for those needed only at run time. Browse libraries and their latest versions on Maven Central, and run ./gradlew dependencies to see the resolved dependency tree.
Larger projects are split into several Gradle modules. Register them in settings.gradle.kts, then depend on one module from another.
// settings.gradle.kts
rootProject.name = "shop"
include(":core", ":app")
// inside the dependencies block of app/build.gradle.kts:
// implementation(project(":core"))Now internal declarations in core are invisible to app, so the compiler enforces the boundary between them.
Kotlin Multiplatform (KMP) shares code across the JVM, Android, iOS (via Kotlin/Native), the browser (Kotlin/JS and Kotlin/Wasm) and more. Shared code lives in the commonMain source set, platform code in sets such as jvmMain or iosMain. Common code declares an API with expect, and each platform supplies an actual implementation.
// commonMain
expect fun platformName(): String
fun greeting() = "Hello from ${platformName()}"
// jvmMain
actual fun platformName(): String = "JVM"You can share only business logic and build native UIs per platform, or share the UI as well with Compose Multiplatform. When learning, start with a plain JVM project and explore KMP once you need it.
package sets the namespace; one file can hold many classes and top-level functions.import works for classes and top-level functions alike, and as adds an alias.public; internal limits a declaration to its module.dependencies block of build.gradle.kts, by coordinates or through a version catalog, usually from Maven Central.expect/actual for platform-specific parts.
0 条评论
登录 · 登录后即可发表评论。
来发表第一条评论吧。