kotlin let表达示_Kotlin示波器功能:常用

kotlin let表达示

One of the main reasons developers are attracted to kotlin is how concise it is to write. Scope functions are one of the ways to write such concise code. According to the official documentation:

开发人员被kotlin吸引的主要原因之一是编写的简洁性。 范围函数是编写此类简洁代码的方法之一。 根据官方文件:

The scope functions do not introduce any new technical capabilities, but they can make your code more concise and readable.

作用域函数没有引入任何新的技术功能,但是它们可以使您的代码更加简洁和易读。

The standard or scope functions that are provided by the language are let, run, apply, also, with.

该语言提供的标准或作用域函数可以一起使用,运行,应用和使用。

Scope functions execute a block of code for a particular object within its context using a lambda expression. But, it's not just about writing less code.

范围函数使用lambda表达式为特定对象在其上下文中执行代码块。 但是,这不只是编写更少的代码。

To use these functions, we must understand couple of things.

要使用这些功能,我们必须了解几件事。

1.“这个”和“它” (1. ‘this’ and ‘it’)

Inside a lambda of a scope function, this (lambda receiver) is used to access the context object. The same object can be accessed by using it (lambda argument). In general, both can perform similar things.

在作用域函数的lambda中, (lambda接收器)用于访问上下文对象。 可以使用来访问同一对象(lambda参数)。 通常,两者都可以执行类似的操作。

这个 (this)

run, apply, with use ‘this’ to access the context object. General rule of thumb is

运行apply使用' this '访问上下文对象。 一般的经验法则是

Having the context object as a receiver ‘this is recommended for lambdas that mainly operate on the object members: call its functions or assign properties.

对于主要对对象成员进行操作的lambda,建议将上下文对象用作接收器“ this :调用其函数或分配属性。

(it)

let and also use ‘it’ to access the context object. Instead of ‘it’, we can also provide custom name.

let并且使用' it '访问上下文对象。 除了“ it” ,我们还可以提供自定义名称。

Having the context object as ‘it is better when the object is mostly used as an argument in function calls. ‘it’ is also better if you use multiple variables in the code block.

当上下文对象通常在函数调用中用作参数时,将上下文对象设置为“ it 会更好。 如果在代码块中使用多个变量,则“ it”也更好。

2.结果 (2. Result)

The behaviour of scope functions can also be differentiated on the basis of their return values. There are two things to remember:

范围函数的行为也可以根据其返回值加以区分。 有两件事要记住:

  1. apply and also return the context object.

    申请 返回上下文对象。

  2. let, run, and with return the lambda result.

    letrunwith一起返回lambda结果。

Now, I will try to explain the most common practical usages of the functions.

现在,我将尝试解释这些功能的最常见实际用法。

1.让 (1. let)

When should we use let function? Well, there are several scenarios. Most common scenario is null check. How did we usually write null checks?

我们什么时候应该使用let 功能? 好吧,有几种情况。 最常见的情况是null检查 。 我们通常如何编写空检查?

if(person!=null) {
print(person.name);
}

With let it looks simpler :

随着让它看起来更简单:

person?.let{
print(it.name)
}

Another common and practical usage is on result of call chains. Suppose we have list of people and we need to print names of people whose age is greater than 25. We might write something like this :

呼叫链的结果是另一种常见的实用用法。 假设我们有人员列表,并且需要打印年龄大于25岁的人员的姓名。我们可能会这样写:

data class Person(val name: String, val age: Int)
fun coolFunction() {
val persons = mutableListOf(
Person("Vinay", 29),
Person("Manish", 30),
Person("Kunal", 24)
)
val resultList = persons.filter { it.age > 25 }.map { it.name }
println(resultList)
}

let simplifies it in this way :

我们以这种方式简化它:

data class Person(val name: String, val age: Int)
fun coolFunction() {
val persons = mutableListOf(
Person("Vinay", 29),
Person("Manish", 30),
Person("Kunal", 24)
)
persons.filter { it.age > 25 }.map { it.name }.let {
println(it)
}}

Note: This is very simple example of chaining for easier understanding. It is more helpful in real life where there is bit of complexity in chaining.

注意 :这是链接的非常简单的示例,以便于理解。 它在链接有些复杂的现实生活中更有用。

2.运行 (2. run)

run is useful when we initialise an object and perform some operation on that object. All this is done within a single run block. re-scopes the variable it’s used on to. The last expression returns a result.

当我们初始化对象并对该对象执行一些操作时, 运行很有用。 所有这些都在一个运行块内完成。 重新作用域范围内的变量。 最后一个表达式返回结果。

val lengthOfName = Person("Vinay", 29).run {
println("Age is $age")
println("Name is $name")
name.length}print(lengthOfName)

3.申请 (3. apply)

Common use case of apply is object configuration. Below code comparison is self explanatory.

apply的常见用例是对象配置。 下面的代码比较不言自明。

val dialog = CustomDialogFragment(this)
dialog.setCanceledOnTouchOutside(false)
dialog.setMessage("Do you want to cancel this transaction?")
dialog.setPositiveButton("Yes")
dialog.setNegativeButton("No")

if we use apply for configuration of dialog object :

如果我们使用apply来配置对话框对象:

val dialog = CustomDialogFragment(this)
dialog.apply {
setCanceledOnTouchOutside(false)
setMessage("Do you want to cancel this transaction?")
setPositiveButton("Yes" )
setNegativeButton("No" )}

Looks cleaner. Doesn’t it? We don’t have to write “dialog.” again and again.

看起来更干净。 是不是 我们不必写“对话”。 一次又一次。

4.也 (4. also)

Common use of also is for side effects without modifying the object. We can use it for doing some operation on intermediate result. also does not transform the object. It returns same object.

通常用于副作用而无需修改对象。 我们可以使用它对中间结果进行一些操作。 也不会变换对象。 它返回相同的对象。

As per the official document :

根据官方文件:

When you see also in the code, you can read it as “and also do the following with the object.

当您also代码中看到时,可以将其读取为“ ,并对该对象执行以下操作。

val persons = mutableListOf(
Person("Vinay", 29),
Person("Manish", 30),
Person("Kunal", 24)
)
val mappingResult = persons.map { it.name }println(mappingResult)
val filteredResult = mappingResult.filter { it.length > 5 }println(filteredResult)

By using apply, it looks much cleaner, no need to break the chain!

通过使用apply ,它看起来更加干净,无需打断链条!

val persons = mutableListOf(
Person("Vinay", 29),
Person("Manish", 30),
Person("Kunal", 24)
)
val filteredResult = persons
.map { it.name }
.also { println(it) }
.filter { it.length > 5 }println(filteredResult)

5.与 (5. with)

Similar to apply function, with is also used to change properties of an instance i.e. object configuration. Only difference is with is not an extension function. The last expression of with function returns a result. Simply as per docs

Apply函数类似, with也用于更改实例的属性,即对象配置。 唯一的区别不是一个扩展功能。 with函数的最后一个表达式返回结果。 简单地按照文档

In the code, with can be read as “with this object, do the following.”

在代码中,with可以理解为“使用此对象,请执行以下操作”。

data class Person(val name: String, val age: Int, var job: String, var address: String)
fun coolFunction() {
val person = Person("Vinay", 29, "Developer", "Mumbai")
with(person) {
job = "Sr. Developer"
address = "Bangalore"
}
println(person)
}

Do use these functions in your code but be careful. Sometimes the code may look over engineered. So choose valid use cases to use these functions. This is very useful link which sort of explains Dos and Don’ts .

不要在代码中使用这些函数,但要小心。 有时,代码可能看起来过于精心设计。 因此,请选择有效的用例以使用这些功能。 是一个非常有用的链接,其中说明了注意事项。

翻译自: https://medium.com/swlh/kotlin-scope-functions-common-usage-5c72f81f1668

kotlin let表达示

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值