You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesi贸n a prueba de IA

Antes: $249

Currency
$209
Suscr铆bete

Termina en:

0 D铆as
9 Hrs
36 Min
33 Seg

Run

32/37
Resources

How does the run function work in Kotlin?

The run function is a powerful tool in Kotlin that allows you to execute a series of operations on a variable after it has been declared. This function is particularly useful when you need to modify a list of items before using it in other parts of your code. Next, we will explore how you can use run and the benefits it brings.

What is the run function and how is it used?

The run function in Kotlin executes a block of code on the context of the object in which it is called. To explain it in a simple way, you can declare a variable, execute run and perform operations inside this block that will affect the previously declared variable.

For example, suppose you have a list of mobile devices and you want to perform certain operations on this list:

val moviles = mutableListOf("Google Pixel", "Google Pixel 4a", "Huawei Redmi 9", "Xiaomi Mi A3")
moviles.run { removeIf { it.contains("Google") }}println(moviles)

In this example, after declaring the list of moviles devices, we use run to remove all the elements containing "Google". This is possible thanks to the use of contains, which works as a condition evaluating if an element contains a specific value. By running this code, you will see that moviles no longer includes "Google Pixel" and "Google Pixel 4a" devices.

What are the practical applications of the run function?

Using run allows you to easily manipulate and debug data before proceeding with processing in other parts of the program. Here are some situations where run is especially useful:

  • Data Filtering: If you get data from an API or database and need to clean the data before using it, run is ideal.

  • Initial Configuration: Before using a particular object, you can configure specific properties within a run block.

  • Operation Chaining: You can use run together with other scope functions to chain operations without the need to declare additional variables.

How to apply run in combination with other functions in Kotlin?

Kotlin provides several scoping functions that can be combined with run for cleaner and more efficient code. These functions, such as let, also, apply, and with, are used for different purposes when working with objects.

  • let: Use it to perform an operation on an object and return the result.

  • also: Useful when you want to do something additional on an object without modifying its return value.

  • apply: Ideal for initializing objects without the need for multiple lines of configuration.

  • with: Executes a series of operations on an object and returns a result depending on the operations.

Example of combination:

mutableListOf("Samsung Galaxy", "Apple iPhone", "Nokia").apply { add("OnePlus")}.also { list -> println("List before `run`: $list")}.run { removeIf { it.contains("Nokia") } println("List after remove: $this")}

In this fragment, apply adds a new element to the list, also it is used to print the list status before run processes the removal.

In conclusion, the use of functions like run makes the Kotlin programming language continue to stand out for its flexibility and ability to simplify complex tasks within your programs. I encourage you to explore the power of scoping functions and see for yourself how they can improve your workflow and code efficiency - keep learning and experimenting with Kotlin!

Contributions 7

Questions 2

Sort by:

Want to see more contributions, questions and answers from the community?

C贸digo de la clase

fun main(args: Array<String>){
    val moviles = mutableListOf("Samsung A50","Samsung A51","Samsung A52")
            .run{
                removeIf{ movil->movil.contains("A50") }
                this
            }
    println(moviles)
}



<fun main(args: Array<String>) {
    val moviles = mutableListOf("Google Pixel 2XL", "Google Pixel 4a", "Huawei Redmi 9", "Xiaomi mi a3")
        .run{
            removeIf{movil -> movil.contains("Google")}
            this
        }
    println(moviles)
}> 

Funci贸n run 馃弮

En Kotlin, la funci贸n run es una funci贸n de orden superior que se utiliza para realizar operaciones en un objeto y devolver un resultado. Proporciona un contexto en el que puedes acceder a las propiedades y m茅todos del objeto de manera concisa.

La sintaxis b谩sica de run es la siguiente:

objeto.run {
    // Realizar operaciones con el objeto
    // ...
    // Devolver un resultado opcionalmente
}
  • objeto es el objeto en el que deseas realizar las operaciones. Puede ser una variable o una expresi贸n.

  • Dentro del bloque de c贸digo de run, puedes acceder a los miembros del objeto directamente, sin la necesidad de llamar al objeto en cada ocasi贸n. Puedes utilizar los m茅todos y propiedades del objeto como si estuvieras dentro del 谩mbito de ese objeto.

  • Puedes realizar cualquier operaci贸n necesaria dentro del bloque de c贸digo de run. Puedes llamar a m茅todos, acceder a propiedades, realizar c谩lculos, etc.

  • Opcionalmente, puedes devolver un resultado al final del bloque de c贸digo utilizando la 煤ltima expresi贸n. Este resultado se asigna a la variable o se utiliza directamente en el contexto en el que se llama a run.

  • El valor de retorno de run es el resultado de la 煤ltima expresi贸n en el bloque de c贸digo, o bien Unit si no hay ninguna expresi贸n.
    .
    Aqu铆 tienes un ejemplo pr谩ctico para ilustrar c贸mo se utiliza run:

data class Persona(val nombre: String, var edad: Int)

val persona = Persona("Juan", 25)


val resultado = persona.run {
    println("Nombre: $nombre")
    println("Edad: $edad")
    edad += 1
    "隆Hola, $nombre! Tienes $edad a帽os."
}

println(resultado)

En este ejemplo, utilizamos run para acceder a los miembros de persona (nombre y edad) dentro del bloque de c贸digo. Podemos imprimir el nombre y la edad, realizar operaciones como incrementar la edad y luego devolver un saludo personalizado con el nombre y la nueva edad. Finalmente, imprimimos el resultado en la 煤ltima l铆nea.
.
En resumen, run es una funci贸n 煤til en Kotlin que permite trabajar con un objeto en un contexto espec铆fico, accediendo a sus miembros de manera m谩s concisa y devolviendo un resultado opcionalmente. Puede mejorar la legibilidad y la claridad del c贸digo al reducir la necesidad de repetir llamadas al objeto y simplificar las operaciones en 茅l.

fun main(args: Array<String>){
    val moviles = mutableListOf("Samsung A50","Samsung A51","Samsung A52")
            .run{
                removeIf{ movil->movil.contains("A50") }
                this
            }
    println(moviles)
}
fun main(args: Array\<String>) { val mobileDevice = mutableListOf("Google Pixel 2XL", "Asus", "Motorola", "Samsung", "Google Pixel 4A", "Kyocera", "iPhone", "Xiaomi") .run { removeIf {movil -> `movil.contains("Google")}` ` this` ` }` ` println(mobileDevice)` `} `