所以我有一个字符串,我想判断我是否应该一分为二,或者返回一些默认值.如下所示:

val myString = "firstPart-secondPart"
val (first, second) = when (myString.contains("-")) {
        true -> myString.split('-', limit = 2)
        else -> ?? <-- How would i return ("Default1", "Default2") so the destructuring still works?
}

So my question is, how do i return two default strings, so that the deconstructing works? I've used String.split() before in order to deconstruct and it's really nice.

推荐答案

How to return 2 values for destructuring

You need to return a type matching the above type, split returns a list, so you could use this:

listOf("Default1", "Default2")

Full code

val myString = "firstPart-secondPart"
val (first, second) = when (myString.contains("-")) {
        true -> myString.split('-', limit = 2)
        else -> listOf("Default1", "Default2")
}

Why this works

由于两个分支都返回List<String>,所以可以将整个when块视为List<String>,因此可以对其进行分解以从中获取值.

Possible cleanup

val myString = "firstPart-secondPart"
val (first, second) = when {
    myString.contains("-") -> myString.split('-', limit = 2)
    else -> listOf("Default1", "Default2")
}   

假设您要添加更多条件,这可能更有意义,否则IF可能更有意义.

Kotlin相关问答推荐

判断字符串是否除了.&" ",","@""""

如何检测一个值是否是Kotlin中的枚举实例?

如何注入返回通用列表的转换器?

列表在 android WebView 中没有正确迭代

Kotlin 获取继承类的默认 hashCode 实现

在协程上下文中重新抛出异常

将一个列表元素分组为多个组(indexBy)

Kotlin:使用另一个列表和字母顺序对列表进行排序的有效方法

添加 Kapt 插件后 - 执行 org.jetbrains.kotlin.gradle.internal.KaptExecution 时发生故障

有没有办法重用 Job 实例?

找不到 androidsdk.modules

如何使用 Coil 从 URL 获取位图?

如何在 Kotlin 中创建一个打开新活动(Android Studio)的按钮?

取消信号上的kotlin流量采集

Android 与 Kotlin - 如何使用 HttpUrlConnection

应用程序在使用 Google Play 服务时遇到问题

我们如何在Java注释声明中引用Kotlin常量?

递归方法调用在 kotlin 中导致 StackOverFlowError 但在 java 中没有

如何在 IntelliJ IDEA 中禁用粘贴时将 Java 转换为 Kotlin?

如何在 Kotlin 中按字母顺序对字符串进行排序