Kotlin scope functions to send to Java developers

What is a scope function?

Generic functions defined in Kotlin's standard library. Since it is a generic function, it can be applied to any type. You can write more Kotlin-like code by using the scope function.

let and run

It is an image like the map function of Stream.

val str: String = "5963"

//Convert the variable str to an Int
//When using let
val i: Int = str.let { it.toInt() }

//Convert the variable str to an Int
//When using run
val i2: Int = str.run { this.toInt() }

The lambda expression that follows let has one argument. This argument is a reference to str. The lambda expression that follows run has no arguments. Instead, this reference in this lambda expression is str. The result of the lambda expression is the return value of let, run.

Also, the object that the function is called, such as the variable str in this example, is called the ** Lacy bar object **.

Where to use

fun getName(): String? = ""
fun makeGreeting(name: String) = "Hello, $name"

fun greet(): String? {
    val name = getName()
    if (name == null) {
        return null
    }

    return makeGreeting(name)
}

In the greet () function Pass the result of getName () to themakeGreeting ()function and The result is the return value of the greet () function.

However, the return value of getName () is a nullable type, so a null check is required once. Let's rewrite this using let.

fun greet(): String? {
    return getName()?.let { makeGreeting(it) }
}

Call let with a safe call to the result of getName (). This way, you can write pretty neatly. This is useful for safe calls and for passing the result of a safe cast as a function argument. (Of course, it is often used in other cases as well.)

apply and also

Similar to let and run, but the return value is always the receiver object.

val str: String = "5963"

//Standard output of variable str
//When also is used
val str2: String = str.also { print(it) }

//Standard output of variable str
//When using apply
val str3: String = str.apply { print(this) }

Where to use

class Person {
    var firstName: String? = null
    var middleName: String? = null
    var lastName: String? = null
}

fun registerNewPerson() : Person {
    val person = Person()
    person.firstName = "Kumiko"
    person.middleName = "Susan"
    person.lastName = "Yamamoto"
    return person
}

The registerNewPerson function creates a new instance of Person and returns it. It just initializes Person, but it has to be put in a variable once.

Let's use ʻalso`.

fun registerNewPerson() : Person {
    return Person().also {
        it.firstName = "Kumiko"
        it.middleName = "Susan"
        it.lastName = "Yamamoto"
    }
}

It can be implemented without creating a temporary variable for Person. When dealing with objects that are not builder patterns, etc. The initialization process of the object is organized in the scope function, which improves readability.

with

with is a little strange. It's like run, which passes a receiver object as an argument.

val str = "5963"
val i: Int = with(str) { this.toInt() }

Where to use

class Greeter {
    fun greet(): String = "Hello, world"
}

fun greet(greeter: Greeter) = with(greeter) { 
    greet()
}

Use with to make it a single expression function. This reference will change and can be written in a different context.

Recommended Posts

Kotlin scope functions to send to Java developers
Kotlin functions and lambdas to send to Java developers
Kotlin Class to send to Java developers
Kotlin Class part.2 to send to Java developers
Getting started with Kotlin to send to Java developers
Kotlin's Null safety to send to Java developers
I want to implement various functions with kotlin and java!
Generics of Kotlin for Java developers
[Android] Convert Android Java code to Kotlin
Convert all Android apps (Java) to Kotlin
Introduction to kotlin for iOS developers ⑥-Kotlin creation
Java: How to send values from Servlet to Servlet
Interoperability tips with Kotlin for Java developers
Introduction to kotlin for iOS developers ④-Type
Memo for migration from java to kotlin
Introduce Kotlin to your existing Java Maven Project
I want to send an email in Java.
Initial settings for rewriting Java projects to Kotlin
Java variable scope (scope)
Java variable scope
[Java] Introduction to Java
Introduction to kotlin for iOS developers ③-About gradle
What I did when I converted java to Kotlin
Introduction to java
Java session scope
Introduction to kotlin for iOS developers ①-Environment construction
Where Java programmers tend to trip over Kotlin
Corresponds to Scope
Introduction to kotlin for iOS developers ②-Project creation
How to write Java String # getBytes in Kotlin?
What Java inexperienced people did to study Kotlin
How to call functions in bulk with Java reflection
Mastering Kotlin ~ Convert Java File to Kotlin File Road to Graduation ~ Part 3
Mastering Kotlin ~ Convert Java File to Kotlin File Road to Graduation ~ Part 2
Send me a roadmap to becoming a full-fledged Java engineer
Mastering Kotlin ~ Convert Java File to Kotlin File Road to Graduation ~ Part 1
I want to transition screens with kotlin and java!
[Introduction to Java] Variable scope (scope, local variables, instance variables, static variables)
Changes from Java 8 to Java 11
Sum from Java_1 to 100
Kotlin's improvements to Java
[Java, Kotlin] Type Variance
From Java to Ruby !!
Introduction to java command
How to use trained model of tensorflow2.0 with Kotlin / Java
How to deploy a kotlin (java) app on AWS fargate
Java Library-Alibi Cloud's LOG Java Producer helps send data to log services