concept foo in category scala

appears as: foo
Scala in Depth

This is an excerpt from Manning's book Scala in Depth.

Defining named parameters in Scala is easy, it’s required syntax. Whatever name you declare for a parameter is the name you can use when calling it. Let’s define a simple Foo class with a single method foo, but with several parameters. These parameters will be set with default values. The following listing shows the various types of usage:

The foo method is defined as taking a type M that’s parameterized by an unknown type. The _ keyword is used as a placeholder for an unknown, existential type. Existential types are covered in more detail in section 6.5. The next statement calls the method foo with a type parameter of Callback and an argument of x, defined in the earlier example. This would not work with the Function1 type directly.

scala> foo[Function1](x)
<console>:9: error: Function1 takes two type parameters, expected: one
       foo[Function1](x)

The foo method can’t be called directly with the Function1 type because Function1 takes two type parameters and the foo method expects a type with only one type parameter.

In the preceding example, the Outer class defines a nested trait Inner along with two methods that use the Inner type. Method foo uses a path dependent type and method bar uses a type projection. Variables x and y are constructed as two different instances of the Outer class. The reference to the y member of an instance of Outer displays its type, java.lang.Object with x.Y when we type this into the REPL. This type displays with the variable instance of Outer, which is x. This is what we meant earlier by our path. To access the correct type Y, you must travel the path through the x variable. If we call the foo method on x using the Inner instance from the same x variable, then the call is successful. But using the Inner instance from the y variable causes the compiler to complain with a type error. The type error explicitly states that it’s expecting the Inner type to come from the same instance as the method call—the x instance.

The bar method was defined using a type projection. The instance restriction isn’t in place as it was for the foo method. When calling the bar method on the x instance using the inner type from the y instance, the call succeeds. This shows that although path-dependent types ( foo.Bar ) require the Bar instances to be generated from the same foo instance, type projections (Foo#Bar ) match any Bar instances generated from any Foo instances. Both path-dependent and type projection rules apply to all nested types, including those created using the type keyword.