我们还应用Kotlin Scope函数运行

Scope Functions

在Kotlin中,作用域函数允许在对象的上下文中执行功能,即代码块。 然后可以在该临时范围内访问该对象,而无需使用名称。 尽管使用范围函数所做的任何事情都可以完成,但是它们使您能够以不同的方式构造代码。 使用它们可以提高可读性,并使您的代码更简洁。

Kotlin标准库提供了四种不同类型的范围函数,可以通过它们引用上下文对象的方式和它们返回的值进行分类。 作用域函数将上下文对象称为函数参数或一个功能接收器。 作用域函数的返回值为功能结果或者上下文对象。

可用的功能是让,也,应用,跑,and 与。 下表基于访问上下文对象的方式以及如上所述的返回类型,总结了每个函数的特性:

上下文对象作为函数参数上下文对象作为函数接收器返回:函数结果让跑,与返回:上下文对象也应用

和...之间的不同跑和与仅在于它们的调用方式。 虽然所有其他范围功能都实现为扩展功能,与是常规功能。

既然我已经提到了诸如函数接收器和扩展函数之类的概念,那么在继续进行范围函数的详细说明之前,先对它们进行简要说明是有意义的。 如果您已经熟悉Kotlin中的功能接收器和扩展功能,则可以跳过下一部分。

Function Arguments, Extension Functions, Receivers

Kotlin允许将功能视为值。 这意味着您可以通过作为参数其他功能。 使用::运算符,您可以将方法转换为函数值。 为了提高可读性,可以将最后一个函数参数放在参数列表之外。

以下示例说明了如何通过定义高阶函数来实现此目的结合,它带有一个函数参数F。 我们正在使用加 method From the 整数 class and with an anonymous Function literal both within the and outside oF the argument list:

// Apply function argument f to integers a and b
fun combine(a: Int, b: Int, f: (Int, Int) -> Int): Int = f(a, b)

// Using the plus method as a function value
combine(1, 2, Int::plus)

// Passing a function literal
combine(1, 2, { a, b ->
    val x = a + b
    x + 100
})

// Passing it outside of the argument list
combine(1, 2) { a, b ->
    val x = a + b
    x + 100
}

扩展功能是扩展您不一定在控制之下的现有类或接口的方法。 在类上定义扩展函数可以让您在该类的实例上调用此方法,就像它是原始类定义的一部分一样。

以下示例在上定义了扩展功能整数返回绝对值:

fun Int.abs() = if (this < 0) -this else this

(-5).abs() // 5

函数文字接收者 are similar to extension functions as the 接收者 object is accessible within the function through 这个. The following code snippet defines the extension function from before but 这个 time as a function literal with 接收者:

val abs: Int.() -> Int = { if (this < 0) -this else this }

(-5).abs() // 5

A common use case for function literals with receivers are type-safe builders. Now that we have covered the basics let's look at the five scope functions individually.

Let, Also, Apply, Run, With

Let

的让作用域函数使上下文对象可用作函数参数,并返回函数结果。 一个典型的用例是对值应用空安全转换。

val x: Int? = null

// null-safe transformation without let
val y1 = if (x != null) x + 1 else null
val y2 = if (y1 != null) y1 / 2 else null

// null-safe transformation with let
val z1 = x?.let { it + 1 }
val z2 = z1?.let { it / 2 }

Also

的应用 scope function makes the context object available as a function argument and returns the context object. This can be used when you are computing a return value inside a function and then want to 应用 some side effect to it before you return it.

// assign, print, return
fun computeNormal(): String {
    val result = "result"
    println(result)
    return result
}

// return and also print
fun computeAlso(): String =
    "result".also(::println)

Apply

的应用作用域函数使上下文对象可用作接收者,并返回上下文对象。 这对于可变对象(例如Java Bean)的“临时构建器”非常有用。

// Java Bean representing a person
public class PersonBean {
    private String firstName;
    private String lastName;
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public String getFirstName() {
        return firstName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    public String getLastName() {
        return lastName;
    }
}
// Initialization the traditional way
val p1 = PersonBean()
p1.firstName = "Frank"
p1.lastName = "Rosner"

// Initialization using apply
val p2 = PersonBean().apply {
    firstName = "Frank"
    lastName = "Rosner"
}

Run and With

的跑作用域函数使上下文对象可用作接收者,并返回函数结果。 它可以与接收器一起使用,也可以不与接收器一起使用。 在没有接收方的情况下使用它时,可以使用局部范围的变量来计算表达式。 通过使用接收器,跑可以在任何对象上调用,例如 连接对象。

// compute result as block result
val result = run {
    val x = 5
    val y = x + 3
    y - 4
}

// compute result with receiver
val result2 = "text".run {
    val tail = substring(1)
    tail.toUpperCase()
}

的与功能完全一样跑但实现为常规功能而不是扩展功能。

val result3 = with("text") {
    val tail = substring(1)
    tail.toUpperCase()
}

Summary

在这篇文章中,我们了解了范围函数让,也,应用,跑,and 与. They differ in the way they refer to the context object and the value they return. Combined 与 the concepts of function arguments,extension functions and receivers,scope functions are a useful tool to produce more readable code.

您如何看待范围函数? 您曾经在一个项目中使用过它们吗? 您还记得何时使用哪一个? 在评论中让我知道您的想法!

References

from: https://dev.to//frosnerd/let-s-also-apply-run-with-kotlin-scope-functions-1ci4

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值