kotlin中的常用运算符_如果Kotlin中的Elvis运算符为null,请改用它

kotlin中的常用运算符

介绍 (Introduction)

“I want to use that value, but if it’s null, then I can use this non-null value instead.”

“我想使用该值,但是如果它为null,那么我可以改用该非null值。”

A lot of times, we are faced with the above situation while we are coding our application. It is probably one of the most common cases to handle in our application code.

很多时候,我们在编写应用程序时都会遇到上述情况。 在我们的应用程序代码中,这可能是最常见的情况之一。

Different programming languages offer different ways of doing it, but today, we are going to take a look at how Kotlin does it.

不同的编程语言提供了不同的实现方式,但是今天,我们将看看Kotlin是如何做到的。

Say hi to the Elvis operator! It is denoted as ?:.

跟猫王操作员打招呼! 它表示为?:

何时使用Elvis操作员 (When to Use the Elvis Operator)

The time to use the Elvis operator is when we are expecting a nullable value and need to handle it to avoid the famous NullPointerException.

使用Elvis运算符的时机是我们期望可为空的值,并且需要对其进行处理以避免著名的NullPointerException

Some examples of the use cases include:

用例的一些示例包括:

  • Querying something from a database by primary key which may return no record.

    通过主键从数据库中查询某些内容,这可能不会返回任何记录。
  • Mapping from one object to another where one or more of the fields may be null.

    从一个对象映射到另一个,其中一个或多个字段可能为空。

如何使用猫王操作员 (How to Use the Elvis Operator)

The syntax to use the Elvis operator is pretty simple and straightforward.

使用Elvis运算符的语法非常简单明了。

val result = x ?: y

This basically says to use x if the value is not null, otherwise use y. The expression on the right-hand side of the Elvis operator or y in this case, is only evaluated in the case where x is null.

这基本上说,使用x ,如果该值不null ,否则使用y 。 仅在xnull的情况下才对Elvis运算符右侧的表达式或y在这种情况下)进行评估。

y can be a value, return an expression or throw an expression.

y可以是一个值, return一个表达式或throw一个表达式。

Let’s go through a few examples.

让我们来看几个例子。

查询可能不返回记录的表 (Query a Table Which May Return No Record)

Below is a function that does GetItem on a DynamoDB table based on a primary key customerId and returns the map of its item, if it exists.

下面是一个函数,该函数基于主键customerIdDynamoDB表上执行GetItem并返回其项的映射(如果存在)。

Then, we want to get the customer’s email and if it does not exist, we want our application to throw an Exception.

然后,我们要获取客户的电子邮件,如果不存在,我们希望我们的应用程序抛出Exception

This is how we would do it using the Elvis operator.

这就是我们使用Elvis运算符的方式。

val email = getCustomerInfo("123")?.get("emailAddress")?.s() ?: throw IllegalArgumentException("email should exist")

在可为空的字段上提供默认值 (Give a Default Value on a Nullable Field)

In some cases, we need a value from one object to be assigned to another object. Let’s say we have the following dataclass named Address.

在某些情况下,我们需要将一个对象中的值分配给另一个对象。 假设我们有以下名为Address dataclass

data class Address(val streetNumber: Int, val streetAddress: String, val streetSuffix: String?)

We have a simple function to return the full concatenated address like this.

我们有一个简单的函数可以像这样返回完整的串联地址。

fun returnFullAddress(address: Address): String {
val fullAddress = address.streetNumber.toString() + " " + address.streetAddress + " " + (address.streetSuffix ?: "")
return fullAddress.trim()
}

Then, we can use it to handle the nullable streetSuffix field like this.

然后,我们可以使用它来处理可为空的streetSuffix字段,如下所示。

val address = Address(12, "John Drive", null)
returnFullAddress(address)// 12 John Drive

连锁猫王运营商 (Chain Elvis Operator)

We can also chain the Elvis operator.

我们还可以链接Elvis运算符。

Remember that the Elvis operator will only evaluate the expression to the right (or we call it the right operand) when the expression to the left is null.

请记住,当左侧的表达式为null时,Elvis运算符将仅对右侧的表达式求值(或我们将其称为右侧操作数)。

结语 (Wrap Up)

The Elvis operator is really handy to use when you have a situation where you expect a null value and want to handle it nicely.

如果您期望null值并希望很好地处理它,则Elvis运算符非常方便使用。

Hopefully, this short tutorial gives you an understanding of when and how to use the operator.

希望这篇简短的教程可以使您了解何时以及如何使用运算符。

翻译自: https://medium.com/better-programming/elvis-operator-in-kotlin-if-null-then-use-this-instead-e4989677a9b1

kotlin中的常用运算符

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值