学习Kotlin一定绕不开 run/let/apply/also 这四兄弟,它们是 Kotlin 使用频率最高的扩展方法(扩展方法在之前文章有介绍),它们也被称为作用域函数(scope functions)。今天我们就来了解一下它们。本文依然是按代码比较,字节码分析,和扩展思考三个方面进行分析。 搞懂其中一个,其他作用域函数可以视为其变种。这篇文章...
Kotlin作用域函数(Scope Functions) 在Kotlin 中,let、run、also、apply 和with是标准库中提供的几个非常有用的作用域函数(Scope Functions)。它们的主要作用是在对象的上下文中执行代码块,并且每个函数在返回值和使用方式上有所不同。 1. let 作用:在非空对象上执行代码块,并将对象作为参数传递到代码块中。 返回...
Kotlin 的 Scope Functions 包含:let、run、with、apply、also 等。本文着重介绍其中最常用的 let、run、apply,以及如何优雅地使用他们。 1.1 apply 函数的使用 apply 函数是指在函数块内可以通过 this 指代该对象,返回值为该对象自己。在链式调用中,我们可以考虑使用它,从而不用破坏链式。 代码语言:javascript 代码...
Written by: baeldung Kotlin Functions 1. Overview Scope functions are very useful, and we use them frequently in Kotlin code. In this tutorial, we’ll explain what they are and also provide some examples of when to use each one. 2. also First, let’s take a look at the mutation ...
Kotlin和Java相比提供了很多语法糖,其目的当然是为了提高程序员的编码效率,但是其中一些过于灵活导致增加了其正确使用的难度,其中 Scope Functions 就属于这一类。曾几何时,面对 apply、also、let、run还有with是不是傻傻分不清?不要羞愧,因为你不是一个人!(千万不要问:那我是什么...? 如果你非要这么问,我想大概...
Scope Functions do not introduce new technical capabilities, nor do they have a real impact on performance. Well, they are here for the same reason that the Kotlin Language was intended for. Making…
Scope functions in Kotlin are powerful tools that can make the code more concise but, like any powerful tool, can also ruin it if not used properly. This article covers the typical scope function issues and gotchas and offers mitigation practices....
suspending functions 就是带有 suspend 关键字的函数。第一 对于用户而言这个关键是是提示用户这个方法只能在 Coroutine 或者其他带有suspend的函数内调用。第二所有被suspend修饰的方法在编译之后都会被动态修改方法的声明,对于没有参数的方法会添加一个Continuation类型的参数,若是存在参数则会参数列表最后添加一个Continuati...
Kotlin协程必须运行在dispatcher里面,协程可以将自己suspend,dispatcher负责resume它们。 有下面三种Dispatcher: Dispatchers.Main:在主线程运行协程。 :该dispatcher适合执行磁盘或网络I/O,并且经过优化。 Dispatchers.Default:该dispatcher适合执行占用大量CPU资源的工作(对列表排序和解析JSON),并且经过优化。
首先,您需要通过手动创建coroutine作用域的提供程序,或者使用像dagger这样的注入框架,使您的协同作用域以...