1.5 Calling Functions and Methods
Scala has functions in addition to methods. It is simpler to use mathematical functions such as min or pow in Scala than in Java—you need not call static methods from a class.
sqrt(2) // Yields 1.4142135623730951 pow(2, 4) // Yields 16.0 min(3, Pi) // Yields 3.0
The mathematical functions are defined in the scala.math package. You can import them with the statement
import scala.math._ // In Scala, the _ character is a "wildcard," like * in Java
We discuss the import statement in more detail in Chapter 7. For now, just use import packageName._ whenever you need to import a particular package.
Scala doesn’t have static methods, but it has a similar feature, called singleton objects, which we will discuss in detail in Chapter 6. Often, a class has a companion object whose methods act just like static methods do in Java. For example, the BigInt companion object to the BigInt class has a method probablePrime that generates a random prime number with a given number of bits:
BigInt.probablePrime(100, scala.util.Random)
Try this in the REPL; you’ll get a number such as 1039447980491200275486540240713. Note that the call BigInt.probablePrime is similar to a static method call in Java.
Scala methods without parameters often don’t use parentheses. For example, the API of the StringOps class shows a method distinct, without (), to get the distinct letters in a string. You call it as
"Hello".distinct
The rule of thumb is that a parameterless method that doesn’t modify the object has no parentheses. We discuss this further in Chapter 5.