Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
What if we need to use a variable that is defined outside a nested function? Consider this contrived example: // code-examples/TypeLessDoMore/count-to-script.scala def countTo(n: Int):Unit = { def count(i: Int): Unit = { if (i <= n) { println(i) count(i + 1) } } count(1) } countTo(5) Note that the nested count method uses the n value that is passed as a parameter to countTo . There is no need to pass n as an argument to count . Because count is nested inside countTo , n is visible to it. The declaration of a field (member variable) can be prefixed with keywords indicating the visibility, just as in languages like Java and C#. Similarly the declaration of a non- nested method can be prefixed with the same keywords. We will discuss the visibility rules and keywords in "Visibility Rules" on page 96. Inferring Type Information Statically typed languages can be very verbose. Consider this typical declaration in Java: import java.util.Map; import java.util.HashMap; ... Map<Integer, String> intToStringMap = new HashMap<Integer, String>(); We have to specify the type parameters <Integer, String> twice. (Scala uses the term type annotations for explicit type declarations like HashMap<Integer, String> .) Scala supports type inference (see, for example, [TypeInference] and [Pierce2002]). The language's compiler can discern quite a bit of type information from the context, with- out explicit type annotations. Here's the same declaration rewritten in Scala, with in- ferred type information: import java.util.Map import java.util.HashMap ... val intToStringMap: Map[Integer, String] = new HashMap Recall from Chapter 1 that Scala uses square brackets ( [...] ) for generic type param- eters. We specify Map[Integer, String] on the lefthand side of the equals sign. (We are sticking with Java types for the example.) On the righthand side, we instantiate the actual type we want, a HashMap , but we don't have to repeat the type parameters. Inferring Type Information | 29