En este post te voy a explicar como funcionan los Maps en Scala.
Primeros pasos.
Un Map, es un diccionario. Una colección que recibe una tupla de dos valores. El primer valor representa la llave o Key, el segundo el valor. Puedes agregar y remover pares mediante tuplas.
Inicializar un Map.
Los Map se inicializan con Map. Si los tipos pueden ser inferidos con los parámetros no es necesario especificar los Type Parameters.
//You can initialize the map using tuples. | |
var map = Map("A" -> 1, | |
"B" -> 2, | |
"C" -> 3) | |
var tuple = "D" -> 2 | |
//You can add an additional value with += operator | |
map += tuple | |
//This, will update C pair with the new value | |
map += "C" -> 4 | |
map.foreach(println) |
Obtener datos del Map.
Puedes obtener la colección con todos los keys, todos lo Values, o todos los pares. Si requieres obtener un valor mediante el Key, el Map te va a retornar un Option, necesitas saber cómo tratarlos.
var map = Map("A" -> 1, | |
"B" -> 2, | |
"C" -> 3) | |
def printOption[T](input:Option[T]): Unit = { | |
input match { | |
case Some(value) => println(value) | |
case None => println("None") | |
} | |
} | |
//You can obtain only the values | |
map.values.foreach(println) | |
//Also, you can read only the key of the Map | |
map.keys.foreach(println) | |
//you can iterate over the pairs, if you need. | |
map.foreach(println) | |
//Getting an existent value | |
var singleValue = map.get("A") | |
printOption(singleValue) | |
//Getting a non-existent value. | |
var none = map.get("Z") | |
printOption(none) |
Map methods.
Un método de mapeo es aquel que transforma una colección en otra. Cualquier método que reciba una colección y retorne una nueva con algún valor transformado es un map method.
var map = Map("A" -> 1, | |
"B" -> 2, | |
"C" -> 3) | |
def printOption[T](input:Option[T]): Unit = { | |
input match { | |
case Some(value) => println(value) | |
case None => println("None") | |
} | |
} | |
//You can obtain only the values | |
map.values.foreach(println) | |
//Also, you can read only the key of the Map | |
map.keys.foreach(println) | |
//you can iterate over the pairs, if you need. | |
map.foreach(println) | |
//Getting an existent value | |
var singleValue = map.get("A") | |
printOption(singleValue) | |
//Getting a non-existent value. | |
var none = map.get("Z") | |
printOption(none) |
Referencias:
- https://docs.scala-lang.org/overviews/collections/maps.html
- https://docs.scala-lang.org/overviews/scala-book/collections-maps.html
- NVL in SQL Server - 2023-11-01
- ¿Que es Cake Build? - 2023-02-22
- #How to fix error: MSB4019: The imported project «Microsoft.Data.Tools.Schema.SqlTasks.targets» was not found - 2023-02-20