Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize empty map that has been type aliased

Typically I have been declaring a map in this fashion because I need it to be empty

var myMap: mutable.Map[String, ListBuffer[Objects]] = mutable.Map[String, ListBuffer[Objects]]()

The object type signature is long so I am trying to declare my own type alias as such in a package object like below.

type MyMapType = mutable.Map[String, ListBuffer[Objects]]

The problem is when I try to declare my map with the alias it doesn't seem to work.

var myMap: MyMapType = MyMapType()

I get an error saying

Expression of type ListBuffer[Objects] doesn't conform to expected type MyPackageObject.MyMapType

like image 731
alex Avatar asked Aug 21 '18 21:08

alex


People also ask

How to return an empty Map in Java?

The emptyMap() method of Java Collections is a method that is used to return an empty map such that we can not change the data in map IE it is immutable.

How do I make an empty map in Scala?

The empty() method is utilized to make the map empty. Return Type: It returns an empty map.

How do I return an empty map in Golang?

Create Empty Map in Golang To create an empty Map in Go language, we can either use make() function with map type specified or use map initializer with no key:value pairs given.

How do you access map elements in Scala?

Scala Map get() method with exampleThe get() method is utilized to give the value associated with the keys of the map. The values are returned here as an Option i.e, either in form of Some or None. Return Type: It returns the keys corresponding to the values given in the method as argument.


1 Answers

Try this:

import collection.mutable.{Map, ListBuffer}
type MyMapType = Map[String, ListBuffer[Object]]
var myMap: MyMapType = Map()

The reason why this works: Map() is shortcut for Map.apply(). It's a method invocation on an object called Map. It is the companion object of mutable.Map. Its name belongs to a completely separate set of identifiers: the names of types are independent from names of objects. Therefore, the companion object Map is still called Map. Note that you can omit all the type arguments to .apply() because of the type inference.

like image 144
Andrey Tyukin Avatar answered Nov 15 '22 06:11

Andrey Tyukin