Home > Articles > Programming

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

1.3 Commonly Used Types

You have already seen some of the data types of the Scala language, such as Int and Double. Like Java, Scala has seven numeric types: Byte, Char, Short, Int, Long, Float, and Double, and a Boolean type. However, unlike Java, these types are classes. There is no distinction between primitive types and class types in Scala. You can invoke methods on numbers, for example:

1.toString() // Yields the string "1"

or, more excitingly,

1.to(10) // Yields Range(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

(We will discuss the Range class in Chapter 13. For now, just view it as a collection of numbers.)

In Scala, there is no need for wrapper types. It is the job of the Scala compiler to convert between primitive types and wrappers. For example, if you make an array of Int, you get an int[] array in the virtual machine.

As you saw in Section 1.1, “The Scala InterpreterThe Scala Type System,” on page 1, Scala relies on the underlying java.lang.String class for strings. However, it augments that class with well over a hundred operations in the StringOps class. For example, the intersect method yields the characters that are common to two strings:

"Hello".intersect("World") // Yields "lo"

In this expression, the java.lang.String object "Hello" is implicitly converted to a StringOps object, and then the intersect method of the StringOps class is applied.

Therefore, remember to look into the StringOps class when you use the Scala documentation (see Section 1.7, “Scaladoc,” on page 8).

Similarly, there are classes RichInt, RichDouble, RichChar, and so on. Each of them has a small set of convenience methods for acting on their poor cousins—Int, Double, or Char. The to method that you saw above is actually a method of the RichInt class. In the expression

1.to(10)

the Int value 1 is first converted to a RichInt, and the to method is applied to that value.

Finally, there are classes BigInt and BigDecimal for computations with an arbitrary (but finite) number of digits. These are backed by the java.math.BigInteger and java.math.BigDecimal classes, but, as you will see in the next section, they are much more convenient because you can use them with the usual mathematical operators.

  • + Share This
  • 🔖 Save To Your Account