https://kotlin.desarrollador-android.com/modismos-y-patrones/funciones-estandar/run/
Introducci贸n a Kotlin
Introducci贸n al Curso de Kotlin
Qu茅 es la Java Virtual Machine
Qu茅 es Kotlin
Configuraci贸n del entorno
Instalaci贸n de IntelliJ
Instalaci贸n de IntelliJ en Linux
Kotlin con Visual Studio Code
Hola mundo Kotlin
Hola mundo con Kotlin
Variables en Kotlin
Kotlin y sus tipos de variables
Modificadores y tipos de datos en Kotlin
Operaciones con los tipos de datos en Kotlin
Kotlin y la programaci贸n funcional
Estructuras de control: if
Estructuras de Control: when
Conceptos b谩sicos de Kotlin
Bucles: While y Do While
Ciclos
Null-Safety en Kotlin
Valores nulos, Double bang y c贸mo solucionarlos.
Try Catch
Elvis operator
Collections en Kotlin
Listas
Como ordenar listas con las funciones que tiene Kotlin
Maps
Sets
Libera el potencial de las funciones
驴Qu茅 son las funciones?
Funciones y funciones de extensi贸n
Tipos de par谩metros en las funciones
Lambdas
High Order functions
Scope functions
Let
With
Run
Apply
Also
Proyecto: Bola 8 m谩gica
Creando el men煤 de nuestra bola m谩gica
Contestando aleatoriamente
驴C贸mo continuar tu camino en Kotlin?
You don't have access to this class
Keep learning! Join and start boosting your career
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.
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.
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.
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
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)
}>
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)
}
Want to see more contributions, questions and answers from the community?