The standard library functions are built-in functions in Kotlin that are readily available for use. For example, the following code prints the results of two operations on a collection: If the code block contains a single function with it as an argument, you can use the method reference (::) instead of the lambda: let is often used for executing a code block only with non-null values. Here is a short guide for choosing scope functions depending on the intended purpose: The use cases of different functions overlap, so that you can choose the functions based on the specific conventions used in your project or team. 1. Hence, they can be included into call chains as side steps: you can continue chaining function calls on the same object after them. The provided scope inherits its coroutineContext from the outer scope, but overrides the context’s Job.. Below we'll provide detailed descriptions of the distinctions between scope functions and the conventions on their usage. Similar to C#, Kotlin allows a user to add functions to any class without the formalities of creating a derived class with new functions. In turn, takeUnless returns the object if it doesn't match the predicate and null if it does. Each scope function uses one of two ways to access the context object: as a lambda receiver (this) or as a lambda argument (it). Scope Functions. In this tutorial, we’ll explain what they are and also provide some examples of when to use each one. Avoid nesting scope functions and be careful when chaining them: it's easy to get confused about the current context object and the value of this or it. The Kotlin standard library contains several functions and purpose of each is to execute a block of code within the given context. I am facing this strange issue where my project compiles and runs successfully but in my kotlin scope functions red … run, with, and apply refer to the context object as a lambda receiver - by keyword this. But before going through these examples, let’s consider a Model class “Person” Function is declared with the keyword “fun”. The return value is the object itself. Android studio: Kotlin scope functions Unresolved reference. When we call such a function on an object with a lambda expression provided, it forms a temporary scope. Kotlin provides scope functions, like ’run’, 'with', 'let',‘also’ and 'apply', which execute a block of code within the context of an object. So for example: Additionally, you can ignore the return value and use a scope function to create a temporary scope for variables. Extension functions. Another case for using let is introducing local variables with a limited scope for improving code readability. TL;DR obj.let{it}, obj.run{this}, with(obj){this} - returns result of last line obj.also{it}, obj.apply{this} - returns the same object. In this scope, you can access the object without its name. The scope functions do not introduce any new technical capabilities, but they can make your code more concise and readable. run is related to let in the same way that apply is related to also: Notice that we return a type R like let, making this a transformation function, but we take an implicit this, like apply. Library support for kotlin coroutines. Let’s say you want to do multiple operations on the same object. Grouping function calls … The Kotlin standard library contains several functions whose sole purpose is to execute a block of code within the context of an object. Kotlin Scope Functions are basically provided to manage the variable scopes easily. Recently I was working on a project that is written in Kotlin. So, you can use them when assigning the result to a variable, chaining operations on the result, and so on. Don't use them just for the sake of using them, only do so in cases where it … In Kotlin, functions can be declared at top level in a file, meaning you do not need to create a class to hold a function, which you are required to do in languages such as Java, C# or Scala. These are designed in a way that you can access the variables without even using their names again and again and also you don’t need to manage their scopes. For example, 1. print()is a library function that prints message to the standard output stream (monitor). The inner function has access to all variables in the scope of the outer function. The Kotlin standard library contains several functions whose sole purpose is to execute a block of code within the context of an object. First, we can use let to convert from one object type to another, like taking a StringBuilder and computing its length: Or second, we can call it conditionally with the Elvis operator, also giving it a default value: let is different from also in that the return type changes. If the argument name is not specified, the object is accessed by the implicit default name it. Additionally, when you pass the context object as an argument, you can provide a custom name for the context object inside the scope. public inline fun repeat (times: Int, action: (Int) -> Unit) The repeat function takes an action as an argument and returns Unit, but a higher order function can return any object. The object is then accessible in that temporary scope without using the name. Last modified: January 12, 2021. by baeldung. For objects that don't match the predicate, takeIf returns null and let isn't invoked. In addition to top level functions, Kotlin functions can also be declared local, as member functions and extension functions. There are five scope functions available in Kotlin: let, apply, run, with and also. Hence, having the context object as it is better when the object is mostly used as an argument in function calls. also is good for performing some actions that take the context object as an argument. 2. sqrt() returns square root of a number (Doublevalue) When you run the program, the output will be: Here is a link to the Kotlin Standard Libraryfor you to explore. In turn, let and also have the context object as a lambda argument. Simply put, a mutation function operates on the given object and returns it. The context object is available as a receiver (this). A global CoroutineScope not bound to any job. Use also for actions that need a reference rather to the object than to its properties and functions, or when you don't want to shadow this reference from an outer scope. Another way of seeing it is as logically grouping multiple calls to a given object: In this article, we’ve explored different scope functions, categorized them and explained them in terms of their results. Just to recap, Scope functions are nothing but the functions which define to the scope of the calling object. Function in functions. There are two main differences between each scope function: Inside the lambda of a scope function, the context object is available by a short reference instead of its actual name. The scope functions differ by the result they return: These two options let you choose the proper function depending on what you do next in your code. These functions let you embed checks of the object state in call chains. Kotlin supports functional programming. on it and call let with the actions in its lambda. Creates a CoroutineScope and calls the specified suspend block with this scope. Viewed 680 times 1. In the code, with can be read as “with this object, do the following.”. In addition to scope functions, the standard library contains the functions takeIf and takeUnless. However, when calling the object functions or properties you don't have the object available implicitly like this. 6. [Kotlin pearls 1] Scope Functions. The local function is only accessible within the outer function. In the case of also, an extension method, we provide a lambda that operates on the extended object: It’ll return the object it was invoked on, which makes it handy when we want to generate some side logic on a call chain: Note our use of it, as this will become important later on. Scope functions are very useful, and we use them frequently in Kotlin code. Scope functions are very useful, and we use them frequently in Kotlin code. Additional effects: also 7. The return value is the object itself. Depending on the scope function you use, the object can be accessed using it or this. Non-extension run lets you execute a block of several statements where an expression is required. To do this, call takeIf on the object and then call let with a safe call (?). Function scope. Extension function is the function that takes a receiver, which becomes this inside the function and serves as the context. And we can use the same approach as let with nullability: Our last transformation function is with. Kotlin Basics; 1. But, maybe we don’t want the extra verbosity of an it lambda parameter. Such functions are called Scope Functions. In this scope, we can access the object without its name. Like any other OOP, it also needs a return type and an option argument list. fun T.callMyAnonymousLambda(block: (T) -> Unit) {block(this)} In the above snippet, we declared an extension function with Generics.