1

How does one represent null in scala for collections?

The equivalent for List's would be "Nil" and it would be represented as follows:

Nil.asInstanceOf[Map[String,String]]

What is the equivalent for Maps?

UPDATE The two working solutions that I am aware of, from experimenting as well as from the suggested solutions are "Map()" and "null.asInstanceOf(Map[String,String])". The Map() is not what I intended: i did not want an empty item but actually a non-existent one (aka null in java). I was already aware that Nil is only for Lists: it was intended to illustrate the flavor of entity I was searching for used by Map's. Using "null.asInstanceOf(..)" is not a scala-ish idiom. It appears there are no equivalents for Map ..?

6
  • 1
    "i did not want an empty item but actually a non-existent one (aka null in java)" In this case, Nil isn't what you want for lists; it's an empty list, exactly the same as List() and List.empty. Commented Jan 6, 2014 at 16:50
  • That depends on what the receiving API expects. Commented Jan 6, 2014 at 16:57
  • No, it doesn't. Your API can treat Nil and null as equivalent, but it can't treat Nil and an empty list differently (because Nil is simply an empty list). Commented Jan 6, 2014 at 17:04
  • That's exactly my point: the receiving api may expect a null not an empty list. Commented Jan 6, 2014 at 17:33
  • If it expects null, you can't use Nil. Commented Jan 6, 2014 at 17:41

2 Answers 2

11

The best way do to it is:

val x = Map.empty[String, String]

With a mutable map:

import scala.collection.mutable.{ Map => MMap }

val y = MMap.empty[String, String]
Sign up to request clarification or add additional context in comments.

Comments

7

Nil is just an empty List. It is not related to null in any way.

Scala has null, just like Java, but it should almost always be avoided.

What is your actual goal?

Do you want an empty Map?

val m = Map[String,String]()

Or an empty mutable Map that can be added to?

val m = collection.mutable.Map[String,String]()

Or an Option[Map] that can be initialized later?

val m: Option[Map[String,String]] = None

Or actually a null?

var m: Map[String,String] = null

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.