Jetpack Compose 的 Kotlin

Jetpack Compose 围绕 Kotlin 构建。在某些情况下,Kotlin 提供了特殊的惯用语,使编写好的 Compose 代码更容易。如果您以其他编程语言思考,并将其在脑海中翻译成 Kotlin,您很可能会错过 Compose 的某些强大功能,并且可能难以理解惯用编写的 Kotlin 代码。更多地熟悉 Kotlin 的风格可以帮助您避免这些陷阱。

默认参数

编写 Kotlin 函数时,您可以指定函数参数的默认值,如果调用者没有显式传入这些值,则使用这些默认值。此功能减少了对重载函数的需求。

例如,假设您想编写一个绘制正方形的函数。该函数可能有一个必需参数 sideLength,用于指定每条边的长度。它可能有几个可选参数,如 thicknessedgeColor 等;如果调用者未指定这些参数,函数将使用默认值。在其他语言中,您可能需要编写多个函数

// We don't need to do this in Kotlin!
void drawSquare(int sideLength) { }

void drawSquare(int sideLength, int thickness) { }

void drawSquare(int sideLength, int thickness, Color edgeColor) { }

在 Kotlin 中,您可以编写一个函数并为参数指定默认值

fun drawSquare(
    sideLength: Int,
    thickness: Int = 2,
    edgeColor: Color = Color.Black
) {
}

除了省去编写多个冗余函数的麻烦,此功能还使您的代码更清晰易读。如果调用者未指定参数的值,则表示他们愿意使用默认值。此外,命名参数使查看代码的意图变得容易得多。如果您查看代码并看到如下函数调用,您可能不知道参数的含义,除非您检查 drawSquare() 代码

drawSquare(30, 5, Color.Red);

相比之下,以下代码是自说明的

drawSquare(sideLength = 30, thickness = 5, edgeColor = Color.Red)

大多数 Compose 库都使用默认参数,您编写的可组合函数也应该这样做。这种做法使您的可组合项可自定义,但仍然使默认行为易于调用。因此,例如,您可以像这样创建一个简单的文本元素

Text(text = "Hello, Android!")

该代码与以下更冗长、更多 Text 参数显式设置的代码具有相同的效果

Text(
    text = "Hello, Android!",
    color = Color.Unspecified,
    fontSize = TextUnit.Unspecified,
    letterSpacing = TextUnit.Unspecified,
    overflow = TextOverflow.Clip
)

第一个代码片段不仅更简单、更易读,而且是自说明的。通过仅指定 text 参数,您表明所有其他参数都希望使用默认值。相比之下,第二个代码片段暗示您希望显式设置这些其他参数的值,尽管您设置的值恰好是函数的默认值。

高阶函数和 Lambda 表达式

Kotlin 支持高阶函数,即接收其他函数作为参数的函数。Compose 基于此方法构建。例如,Button 可组合函数提供一个 onClick lambda 参数。该参数的值是一个函数,当用户点击按钮时,按钮会调用该函数

Button(
    // ...
    onClick = myClickFunction
)
// ...

高阶函数与lambda 表达式(求值为函数的表达式)自然结合。如果您只需要函数一次,则无需在其他地方定义它,然后将其传递给高阶函数。相反,您可以直接使用 lambda 表达式在行内定义函数。前面的示例假设 myClickFunction() 在其他地方定义。但是,如果您只在此处使用该函数,则更简单的方法是直接使用 lambda 表达式在行内定义函数

Button(
    // ...
    onClick = {
        // do something
        // do something else
    }
) { /* ... */ }

尾随 Lambda

Kotlin 为调用其最后一个参数是 lambda 的高阶函数提供了一种特殊语法。如果您想将 lambda 表达式作为该参数传递,可以使用尾随 lambda 语法。您不是将 lambda 表达式放在括号内,而是将其放在后面。这在 Compose 中很常见,因此您需要熟悉代码的外观。

例如,所有布局的最后一个参数,例如 Column() 可组合函数,是 content,这是一个发出子界面元素的函数。假设您想创建一个包含三个文本元素的列,并且需要应用一些格式。这段代码可以工作,但非常笨重

Column(
    modifier = Modifier.padding(16.dp),
    content = {
        Text("Some text")
        Text("Some more text")
        Text("Last text")
    }
)

由于 content 参数是函数签名中的最后一个,并且我们将其值作为 lambda 表达式传递,因此我们可以将其从括号中取出

Column(modifier = Modifier.padding(16.dp)) {
    Text("Some text")
    Text("Some more text")
    Text("Last text")
}

这两个示例具有完全相同的含义。大括号定义了传递给 content 参数的 lambda 表达式。

实际上,如果您传递的唯一参数是尾随 lambda(即,如果最后一个参数是 lambda,并且您没有传递任何其他参数),则可以完全省略括号。例如,假设您不需要将修饰符传递给 Column。您可以这样编写代码

Column {
    Text("Some text")
    Text("Some more text")
    Text("Last text")
}

这种语法在 Compose 中非常常见,尤其适用于 Column 等布局元素。最后一个参数是一个 lambda 表达式,定义了元素的子项,这些子项在函数调用后的大括号中指定。

作用域和接收器

某些方法和属性仅在特定作用域内可用。有限的作用域让您可以在需要时提供功能,并避免在不适合时意外使用该功能。

考虑 Compose 中使用的一个示例。当您调用 Row 布局可组合项时,您的内容 lambda 会在 RowScope 中自动调用。这使得 Row 能够公开仅在 Row 中有效的函数。下面的示例演示了 Row 如何为 align 修饰符公开行特定的值

Row {
    Text(
        text = "Hello world",
        // This Text is inside a RowScope so it has access to
        // Alignment.CenterVertically but not to
        // Alignment.CenterHorizontally, which would be available
        // in a ColumnScope.
        modifier = Modifier.align(Alignment.CenterVertically)
    )
}

有些 API 接受在接收器作用域中调用的 lambda。这些 lambda 可以根据参数声明访问在其他地方定义的属性和函数

Box(
    modifier = Modifier.drawBehind {
        // This method accepts a lambda of type DrawScope.() -> Unit
        // therefore in this lambda we can access properties and functions
        // available from DrawScope, such as the `drawRectangle` function.
        drawRect(
            /*...*/
            /* ...
        )
    }
)

如需了解详情,请参阅 Kotlin 文档中的带接收器的函数字面量

委托属性

Kotlin 支持委托属性。这些属性的调用方式就像它们是字段一样,但它们的值通过评估表达式动态确定。您可以通过它们使用 by 语法来识别这些属性

class DelegatingClass {
    var name: String by nameGetterFunction()

    // ...
}

其他代码可以通过以下方式访问该属性

val myDC = DelegatingClass()
println("The name property is: " + myDC.name)

println() 执行时,nameGetterFunction() 将被调用以返回字符串的值。

这些委托属性在处理状态支持的属性时特别有用

var showDialog by remember { mutableStateOf(false) }

// Updating the var automatically triggers a state change
showDialog = true

解构数据类

如果您定义一个数据类,您可以通过解构声明轻松访问数据。例如,假设您定义一个 Person

data class Person(val name: String, val age: Int)

如果您有一个该类型的对象,您可以使用以下代码访问其值

val mary = Person(name = "Mary", age = 35)

// ...

val (name, age) = mary

您经常会在 Compose 函数中看到这种代码

Row {

    val (image, title, subtitle) = createRefs()

    // The `createRefs` function returns a data object;
    // the first three components are extracted into the
    // image, title, and subtitle variables.

    // ...
}

数据类提供了许多其他有用的功能。例如,当您定义一个数据类时,编译器会自动定义 equals()copy() 等有用函数。您可以在数据类文档中找到更多信息。

单例对象

Kotlin 使得声明单例(始终只有一个实例的类)变得容易。这些单例使用 object 关键字声明。Compose 经常使用此类对象。例如,MaterialTheme 被定义为单例对象;MaterialTheme.colorsshapestypography 属性都包含当前主题的值。

类型安全的构建器和 DSL

Kotlin 允许使用类型安全的构建器创建领域特定语言 (DSL)。DSL 允许以更可维护和可读的方式构建复杂的层次结构数据结构。

Jetpack Compose 对某些 API 使用 DSL,例如 LazyRowLazyColumn

@Composable
fun MessageList(messages: List<Message>) {
    LazyColumn {
        // Add a single item as a header
        item {
            Text("Message List")
        }

        // Add list of messages
        items(messages) { message ->
            Message(message)
        }
    }
}

Kotlin 使用带接收器的函数字面量来保证类型安全的构建器。以 Canvas 可组合项为例,它将一个以 DrawScope 作为接收器的函数 onDraw: DrawScope.() -> Unit 作为参数,从而允许代码块调用在 DrawScope 中定义的成员函数。

Canvas(Modifier.size(120.dp)) {
    // Draw grey background, drawRect function is provided by the receiver
    drawRect(color = Color.Gray)

    // Inset content by 10 pixels on the left/right sides
    // and 12 by the top/bottom
    inset(10.0f, 12.0f) {
        val quadrantSize = size / 2.0f

        // Draw a rectangle within the inset bounds
        drawRect(
            size = quadrantSize,
            color = Color.Red
        )

        rotate(45.0f) {
            drawRect(size = quadrantSize, color = Color.Blue)
        }
    }
}

如需详细了解类型安全的构建器和 DSL,请参阅 Kotlin 的文档

Kotlin 协程

协程在 Kotlin 中提供了语言级别的异步编程支持。协程可以暂停执行而不会阻塞线程。响应式界面本质上是异步的,Jetpack Compose 通过在 API 级别采用协程而不是使用回调来解决此问题。

Jetpack Compose 提供了可在界面层中安全使用协程的 API。 rememberCoroutineScope 函数返回一个 CoroutineScope,您可以使用它在事件处理程序中创建协程并调用 Compose suspend API。请参阅下面使用 ScrollStateanimateScrollTo API 的示例。

// Create a CoroutineScope that follows this composable's lifecycle
val composableScope = rememberCoroutineScope()
Button(
    // ...
    onClick = {
        // Create a new coroutine that scrolls to the top of the list
        // and call the ViewModel to load data
        composableScope.launch {
            scrollState.animateScrollTo(0) // This is a suspend function
            viewModel.loadData()
        }
    }
) { /* ... */ }

协程默认按顺序执行代码块。一个正在运行的协程调用挂起函数会暂停其执行,直到挂起函数返回。即使挂起函数将执行转移到不同的 CoroutineDispatcher,这也是如此。在前面的示例中,loadData 不会在挂起函数 animateScrollTo 返回之前执行。

要并发执行代码,需要创建新的协程。在上面的示例中,为了并行化滚动到屏幕顶部和从 viewModel 加载数据,需要两个协程。

// Create a CoroutineScope that follows this composable's lifecycle
val composableScope = rememberCoroutineScope()
Button( // ...
    onClick = {
        // Scroll to the top and load data in parallel by creating a new
        // coroutine per independent work to do
        composableScope.launch {
            scrollState.animateScrollTo(0)
        }
        composableScope.launch {
            viewModel.loadData()
        }
    }
) { /* ... */ }

协程使得组合异步 API 变得更容易。在以下示例中,我们将 pointerInput 修饰符与动画 API 结合使用,以在用户点击屏幕时为元素的位置设置动画。

@Composable
fun MoveBoxWhereTapped() {
    // Creates an `Animatable` to animate Offset and `remember` it.
    val animatedOffset = remember {
        Animatable(Offset(0f, 0f), Offset.VectorConverter)
    }

    Box(
        // The pointerInput modifier takes a suspend block of code
        Modifier
            .fillMaxSize()
            .pointerInput(Unit) {
                // Create a new CoroutineScope to be able to create new
                // coroutines inside a suspend function
                coroutineScope {
                    while (true) {
                        // Wait for the user to tap on the screen
                        val offset = awaitPointerEventScope {
                            awaitFirstDown().position
                        }
                        // Launch a new coroutine to asynchronously animate to
                        // where the user tapped on the screen
                        launch {
                            // Animate to the pressed position
                            animatedOffset.animateTo(offset)
                        }
                    }
                }
            }
    ) {
        Text("Tap anywhere", Modifier.align(Alignment.Center))
        Box(
            Modifier
                .offset {
                    // Use the animated offset as the offset of this Box
                    IntOffset(
                        animatedOffset.value.x.roundToInt(),
                        animatedOffset.value.y.roundToInt()
                    )
                }
                .size(40.dp)
                .background(Color(0xff3c1361), CircleShape)
        )
    }

要了解有关协程的更多信息,请查阅Android 上的 Kotlin 协程指南。