Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to instantiate Unit in Scala?

All I desire is to use some concurrent Set (that appears not to exist at all). Java uses java.util.concurrent.ConcurrentHashMap<K, Void> to achieve that behavior. I'd like to do sth similar in Scala so I created instance of Scala HashMap (or Java ConcurrentHashMap) and tried to add some tuples:

val myMap = new HashMap[String, Unit]()
myMap + (("myStringKey", Unit))

This of course crashed the process of compilation as Unit is abstract and final.

How to make this work? Should I use Any/AnyRef instead? I must ensure nobody inserts any value.

Thanks for help

like image 709
petrbel Avatar asked Oct 25 '14 14:10

petrbel


People also ask

How do I create an instance of a class in Scala?

Instead, Scala has singleton objects. A singleton is a class that can have only one instance, i.e., Object. You create singleton using the keyword object instead of class keyword. Since you can't instantiate a singleton object, you can't pass parameters to the primary constructor.

What is unit function in Scala?

Unit is a subtype of scala. AnyVal. There is only one value of type Unit , () , and it is not represented by any object in the underlying runtime system. A method with return type Unit is analogous to a Java method which is declared void .

What is the meaning of => in Scala?

=> is syntactic sugar for creating instances of functions. Recall that every function in scala is an instance of a class. For example, the type Int => String , is equivalent to the type Function1[Int,String] i.e. a function that takes an argument of type Int and returns a String .

What is Unit return type in Scala?

If you don't specify any return type of a function, default return type is Unit which is equivalent to void in Java. = : In Scala, a user can create function with or without = (equal) operator. If the user uses it, the function will return the desired value.


1 Answers

You can just use () whose type is Unit:

scala> import scala.collection.mutable.HashMap
import scala.collection.mutable.HashMap

scala> val myMap = new HashMap[String, Unit]()
myMap: scala.collection.mutable.HashMap[String,Unit] = Map()

scala> myMap + ("myStringKey" -> ())
res1: scala.collection.mutable.Map[String,Unit] = Map(myStringKey -> ())

This is a comment taken from Unit.scala:

There is only one value of type Unit, (), and it is not represented by any object in the underlying runtime system.

like image 110
Ende Neu Avatar answered Sep 18 '22 23:09

Ende Neu