我们何时应在Kotlin上使用run,let,apply和with的示例 [英] Example of when should we use run, let, apply, also and with on Kotlin

查看:76
本文介绍了我们何时应在Kotlin上使用run,let,apply和with的示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望为每个函数的运行提供一个很好的例子,让我们一起应用

I wish to have a good example for each function run, let, apply, also, with

我已阅读

I have read this article but still lack of an example

推荐答案

所有这些函数都用于切换当前函数/变量的范围.它们用于将属于在一起的事物放在一个位置(通常是初始化).

All these functions are used for switching the scope of the current function / the variable. They are used to keep things that belong together in one place (mostly initializations).

以下是一些示例:

run-返回您想要的任何内容,并将作用域重新定义为this

run - returns anything you want and re-scopes the variable it's used on to this

val password: Password = PasswordGenerator().run {
       seed = "someString"
       hash = {s -> someHash(s)}
       hashRepetitions = 1000

       generate()
   }

现在密码生成器的作用域被重新定义为this,因此我们可以在不使用变量的情况下设置seedhashhashRepetitions. generate()将返回Password的实例.

The password generator is now rescoped as this and we can therefore set seed, hash and hashRepetitions without using a variable. generate() will return an instance of Password.

apply与之类似,但它将返回this:

apply is similar, but it will return this:

val generator = PasswordGenerator().apply {
       seed = "someString"
       hash = {s -> someHash(s)}
       hashRepetitions = 1000
   }
val pasword = generator.generate()

这对于替换Bu​​ilder模式特别有用,并且如果您想重用某些配置.

That's particularly useful as a replacement for the Builder pattern, and if you want to re-use certain configurations.

let-主要用于避免空检查,但也可以替代run.区别在于,this仍将与以前相同,并且您可以使用it访问重新作用域变量:

let - mostly used to avoid null checks, but can also be used as a replacement for run. The difference is, that this will still be the same as before and you access the re-scoped variable using it:

val fruitBasket = ...

apple?.let {
  println("adding a ${it.color} apple!")
  fruitBasket.add(it)
}

上面的代码只有在苹果不为null时,才会将其添加到购物篮中.还要注意,it现在已经不再是可选的了,因此您在这里不会遇到NullPointerException(aka.您不需要使用?.来访问其属性)

The code above will add the apple to the basket only if it's not null. Also notice that it is now not optional anymore so you won't run into a NullPointerException here (aka. you don't need to use ?. to access its attributes)

also-当您想使用apply而不希望遮盖this

also - use it when you want to use apply, but don't want to shadow this

class FruitBasket {
    private var weight = 0

    fun addFrom(appleTree: AppleTree) {
        val apple = appleTree.pick().also { apple ->
            this.weight += apple.weight
            add(apple)
        }
        ...
    }
    ...
    fun add(fruit: Fruit) = ...
}

在这里使用apply会遮盖this,以便this.weight会指向苹果,而不是会指向水果篮.

Using apply here would shadow this, so that this.weight would refer to the apple, and not to the fruit basket.

注意:我毫不客气地从我的博客中获取了示例

Note: I shamelessly took the examples from my blog

这篇关于我们何时应在Kotlin上使用run,let,apply和with的示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆