score:119
Why not to use withDefaultValue(value)?
scala> val m = Map[Int, List[String]]().withDefaultValue(List())
m: scala.collection.immutable.Map[Int,List[String]] = Map()
scala> m(123)
res1: List[String] = List()
score:2
withDefault can also be used.
/** The same map with a given default function.
* Note: `get`, `contains`, `iterator`, `keys`, etc are not affected
* by `withDefault`.
*
* Invoking transformer methods (e.g. `map`) will not preserve the default value.
*
* @param d the function mapping keys to values, used for non-present keys
* @return a wrapper of the map with a default value
*/
def withDefault[B1 >: B](d: A => B1): immutable.Map[A, B1]
Example:
scala> def intToString(i: Int) = s"Integer $i"
intToString: (i: Int)String
scala> val x = Map[Int, String]().withDefault(intToString)
x: scala.collection.immutable.Map[Int,String] = Map()
scala> x(1)
res5: String = Integer 1
scala> x(2)
res6: String = Integer 2
Hope this helps.
score:4
Why do you want to manipulate a map when it has already a method for this?
val m = Map(1L->List("a","b"), 3L->List("x","y","z"))
println(m.getOrElse(1L, List("c"))) //--> List(a, b)
println(m.getOrElse(2L, List("y"))) //--> List(y)
score:11
There's a method withDefaultValue
on Map
:
scala> val myMap = Map(1 -> List(10), 2 -> List(20, 200)).withDefaultValue(Nil)
myMap: scala.collection.immutable.Map[Int,List[Int]] = Map((1,List(10)), (2,List(20, 200)))
scala> myMap(2)
res0: List[Int] = List(20, 200)
scala> myMap(3)
res1: List[Int] = List()
score:25
Rather than using apply
to access the map, you could always use get
, which returns Option[V]
and then getOrElse
:
map.get(k) getOrElse Nil
One great feature of the scalaz functional-programming library is the unary operator ~
, which means "or zero",as long as the value type has a "zero" defined (which List
does, the zero being Nil
of course). So the code then becomes:
~map.get(k)
This is doubly useful because the same syntax works where (for example) your values are Int
, Double
etc (anything for which there is a Zero
typeclass).
There has been a great deal of debate on the scala mailing list about using Map.withDefault
because of how this then behaves as regards the isDefinedAt
method, among others. I tend to steer clear of it for this reason.
Source: stackoverflow.com
Related Query
- How to implement Map with default operation in Scala
- How to deal with complex operation on Map in Scala
- How can I convert Scala Map to Java Map with scala.Float to java.Float k/v conversion
- Spark: How to map Python with Scala or Java User Defined Functions?
- How to substitute an empty string (or null) with a default string concisely in Scala
- How to implement breadth first search in Scala with FP
- How to implement a short-circuit with IO monad in Scala
- How to transpose a map with list values in Scala
- How to implement Java interface in Scala with multiple variable parameter methods (type eraser issue)?
- Update a mutable map with default value in Scala
- How to implement a trait with a generic case class that creates a dataset in Scala
- How do I write a scala extractor for a case class with default parameters?
- How to implement maxBy with multiple max in Scala
- How to implement a custom tail recursive map for lists in Scala
- scala (scanLeft) - how to (functionally) get a Map with cumulated values / frequency
- How to convert Tuples to Map with Set in Scala
- Scala Map with mutable default value always point to the same object
- How to create a scala case class instance with a Map instance
- How to read from textfile(String type data) map and load data into parquet format(multiple columns with different datatype) in Spark scala dynamically
- How to implement generic function in Scala with two argument types?
- how to implement takeUntil with Scala lazy collections
- How can I get Scala Named and Default arguments to work with macros
- How to transform Scala nested map operation to Scala Spark operation?
- How to implement enums with values in Scala 2.12.15
- How to implement db operation in scala functional programming
- How to map multiple Futures and pass them as arguments to a view using Play with Scala
- How to define a type of function with default value in Scala
- Performance Difference Using Update Operation on a Mutable Map in Scala with a Large Size Data
- How to initialize a generic array with a default value in Scala
- How to return a Map with Value Type as String in scala
More Query from same tag
- How to use implicitly with a function?
- IDEA cannot find package
- Scala: How to define the default value for a constructor parameter within the companion object?
- How to select a object field for map value in Scala using groupby
- SBT task to copy property file from project folder to webapp
- How not to require the import of scala.language.relectiveCalls
- How to create unique Hash for each row having null value in column in Spark Scala?
- Convert Java CompletableFuture to TwitterFuture (without any intermediate Future)
- Multi project setup - No main class detected
- Cartesian Product and Map Combined in Scala
- Getting the output of Spark org.apache.spark.sql.Dataset#show() as a String?
- Why are the indexes of Scala tuples 1-based?
- How to retrieve a subset of rows from DataFrame based on condition?
- What is the issue with this sbt file?
- SparkSubmit Exception (NoClassDefFoundError), even though SBT compiles and packages sucessfully
- How do I open Try value in scala and add its values by mapping them
- What is the proper way to code a read-while loop in Scala?
- Multiple pattern matches with same input variable
- Scala Removing Generic Type Information
- Why scala can't infer the type in a partial method?
- Scala, prepend a list of variables to the beginning of each list in a list
- Type referrence mechanisms in Scala
- How do I accept a generic that extends a class in Scala
- How to implement multiple Silhouette Authenticators?
- What does '_._2' mean in spark
- Difference in asymptotic time of two variants of flatten
- Composing functions with multiple arguments vs multiple argument lists
- Why in runtime the app have java.lang.NoClassDefFoundError: reactivemongo/api/bson/SafeBSONWriter
- how to serialize case classes with traits with jsonspray
- Getting map function with custom CanBuildFrom and Builder to work in Scala