Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use primitives in Scala?

Can I use primitives in Scala?

The use case is for storing billions of ints, so the difference between 4 bytes (for an int) and 16 bytes (for an Integer) is important.

like image 640
S0rin Avatar asked Oct 26 '12 09:10

S0rin


People also ask

What are primitives in Scala?

Scala has no primitives in Java. In other words, when coding in Scala, everything is an object. However, the compiler will compile your code down to primitive math (if possible), so you don't lose performance.

Does Scala have primitive types?

Delta Lake with Apache Spark using ScalaThere are no primitive types like in Java. This means that you can call methods on an Int, Long, etc.

What is the use of primitives?

Primitives are used to create more complex pieces of code. Primitive types are also known as built-in types or basic types.

Can we use primitives in collections?

Since primitive types cannot be used in Collections or Generics, each time i is added to numbers a new Integer object is created.


2 Answers

If you want Scala to store unboxed primitives, you could use Array[Int] but refrain from using any cool Scala collection method on it (because it will force boxing).

If you look for immutable collections of primitives types, you can have a look at Debox, which provides specialised Buffers, Sets and Maps. The project is still evolving but it is very promising.

like image 110
paradigmatic Avatar answered Sep 28 '22 07:09

paradigmatic


You can use the @specialised annotation to let the compiler create specialised instances of a class for you. See this article.

class Container[@specialized(Int) T](value: T) {
  def apply(): T = value
}
like image 25
Malte Schwerhoff Avatar answered Sep 28 '22 07:09

Malte Schwerhoff