kotlin 条件语句_Kotlin中写条件语句的新方法

本文介绍了Kotlin中编写条件语句的创新方法,详细探讨了如何利用这种新方式来提升代码的可读性和简洁性。
摘要由CSDN通过智能技术生成

kotlin 条件语句

Ever since Kotlin was born, it has been one of the preferred languages to develop apps for Android devs around the globe. People love Kotlin for various reasons: extension functions, ease of doing things, less boilerplate code, cross-platform support, and more.

自Kotlin出生以来,它一直是为全球Android开发人员开发应用程序的首选语言之一。 人们喜欢Kotlin的原因有很多:扩展功能,易于操作,减少样板代码,跨平台支持等等。

Yet there are many of us who overlook the potential of little things in Kotlin. For example, I still see many of my teammates use if and else if nested statements occasionally.

然而,我们当中许多人却忽略了Kotlin小事情的潜力。 例如,我仍然看到我的许多队友偶尔使用ifelse if嵌套语句。

With Kotlin, we can have a unique yet simple solution that can deal with multiple problems. For example, the when statement can replace all the conditional statements in any Kotlin project if you’re smart enough to use it.

使用Kotlin,我们可以拥有一个独特而简单的解决方案,可以解决多个问题。 例如,如果您足够聪明,可以使用when语句替换任何Kotlin项目中的所有条件语句。

Without any further delay, let’s learn how to use the when statement in Kotlin effectively.

不用再拖延了,让我们学习如何有效地在Kotlin中使用when语句。

将If / Else替换为When (Replace If/Else With When)

If/Else statements have been around since the dawn of programming. Regardless of the platform/language, developers tend to use them for conditional execution.

自编程开始以来就出现了If / Else语句。 无论平台/语言如何,开发人员都倾向于将它们用于条件执行。

Thanks to Kotlin, we no longer need to use the old style. The when statement deals with all types of conditional statements, including if/else, and their nested statements can be replaced with when as well.

感谢Kotlin,我们不再需要使用旧样式。 when语句处理所有类型的条件语句,包括if / else ,其嵌套语句也可以用when替换。

Let’s consider a simple example where we return the emoji based on the input string. If you consider writing conventionally, we might do the following:

让我们考虑一个简单的示例,在该示例中,我们根据输入字符串返回表情符号。 如果您考虑按常规编写,我们可能会执行以下操作:

fun getEmoji(input : String){
    
    if ("Apple"){
        print(🍎)
    } else if ("Mango"){
        print(🥭)
    } else if ("Strawberry"){
        print(🍓)
    } else if ("Grapes"){
        print(🍇)
    }
    
}

We can rewrite the code above using the when statement in Kotlin. It provides better readability than if/else:

我们可以使用Kotlin中的when语句重写上面的代码。 它比if / else提供更好的可读性:

fun getTheEmoji(input : String){


    when(input){
        "Apple" -> print(🍎)
        "Mango" -> print(🥭)
        "Strawberry" -> print(🍓)
        "Grapes" -> print(🍇)
    }
    
}

用时间替换开关盒 (Replace Switch Case With When)

Similar to if/else statements, switch case is one of the ancient ways to deal with conditional execution. In Kotlin, we can replace switch case and if/else with when in a similar way in order to maintain consistency when implementing conditional execution.

if / else语句类似, switch case是处理条件执行的古老方法之一。 在Kotlin中,我们可以用类似的方式将switch case和if / elsewhen替换,以在实现条件执行时保持一致性。

First, let’s see how to implement the example above with the switch in a traditional way:

首先,让我们看看如何以传统方式使用switch来实现上述示例:

private void switchexample(String input){
    switch (input){
        case "Apple":
            print(🍎);
        case "Mango":
            print(🥭)
        case "Strawberry":
            print(🍓)
        case "Grapes":
            print(🍇)
    }
}

Switch case can be replaced with the when statement similarly to if/else. This will make the code more readable, consistent, and provide quick adaptability to new developers.

Switch的情况下可以用更换when声明类似if / else 。 这将使代码更具可读性,一致性,并为新开发人员提供快速的适应性。

使用When块返回值 (Return Values With When Block)

Until now, you’ve seen the ability of the when block in Kotlin to replace conditional statements. But it can do more than that. For example, it can return the values from the conditional blocks after executing the necessary steps. Have a look:

到目前为止,您已经看到Kotlin中的when块替换条件语句的能力。 但是它可以做的还不止这些。 例如,它可以在执行必要的步骤后从条件块返回值。 看一看:

fun showOutPut(input : String){
    tv_display.text = when(input){
        "Apple" -> 🍎
        "Mango" -> 🥭
        "Strawberry" -> 🍓
        "Grapes" -> 🍇
        else -> "Not a Fruit"
    }
}

This type of code implementation saves tons of time for developers.

这种类型的代码实现为开发人员节省了大量时间。

随时间的任意条件 (Arbitrary Conditions With When)

We can use one or more checks to execute a block with the when operator:

我们可以使用一个或多个检查来使用when运算符执行一个块:

fun getTheEmoji(input : Int){
  
    when(input) {
        0 -> print(🍎)
        1, 2 -> print(🥭)
        in 3..7 -> print(🍓)
        !in 8..12 -> print(🍇)
        else -> "No match found"
    }
  
}

Only one case has to match the respective block of code to be executed, so the comma acts as an OR operator. In addition to that, the when block executes inner conditions like range (as shown above).

只有一种情况必须匹配要执行的相应代码块,因此逗号充当OR运算符。 除此之外, when块还会执行诸如范围之类的内部条件(如上所示)。

不带参数时使用 (Using When Without an Argument)

Until now, we’ve used when with an argument. But the real potential of when is that we can use it without any arguments, which I’ve never seen before using Kotlin. Have a look:

到目前为止,我们一直使用带参数的when 。 但是when的真正潜力在于我们可以不带任何参数地使用它,这在使用Kotlin之前从未见过。 看一看:

val number = 1
val name = "Strawberry"
fun getTheEmoji(){
    when {
        number == 10 -> print(🔟)
        name.equals("Strawberry",true) -> print(🍓)
    }
}

It acts as a simple if/else block with class-level variable conditions.

它充当具有类级变量条件的简单if / else块。

将实例与何时进行比较 (Comparing Instances With When)

We can also check whether the given operator is an instance of a particular type at runtime using the is operator. The is operator is similar to the instanceof operator in Java. We can use is and !is operators inside a when block. Have a look:

我们还可以使用is运算符在运行时检查给定的运算符是否为特定类型的实例。 is运算符类似于Java中的instanceof运算符。 我们可以在when块中使用is!is运算符。 看一看:

when (x) {
    is Int -> print(🔟)
    is String -> print(🍓)
    is IntArray -> print(x.sum())
}

使用时间的优势 (Advantages of Using When)

  • In Java, a few conditional statements like switch can only be operated with primitive data types, enums, and string classes. But Kotlin allows when to be used with user-defined types. This makes it more developer-friendly.

    在Java中,一些条件语句(如switch只能与原始数据类型,枚举和字符串类一起使用。 但是Kotlin允许when与用户定义类型一起使用。 这使其对开发人员更加友好。

  • Unlike with Java, Kotlin’s when can be used with dynamic values such as return types of functions.

    与Java不同,Kotlin的when可与动态值(例如函数的返回类型)一起使用。

  • We can also check whether the given argument is present in collections using the in operator, which acts as contains.

    我们还可以使用in运算符(充当contains检查集合中是否存在给定参数。

奖金 (Bonus)

To learn more about Kotlin, read the previous parts of this Advanced Programming With Kotlin series:

要了解有关Kotlin的更多信息,请阅读“使用Kotlin进行高级编程”系列的先前部分:

结论 (Conclusion)

That is all for now. I hope you learned something useful.

到此为止。 我希望你学到了一些有用的东西。

翻译自: https://medium.com/better-programming/a-new-way-to-write-conditional-statements-in-kotlin-a3c029e417dc

kotlin 条件语句

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值