In scala-arm project, I see code like this:
def managed[A : Resource : Manifest](opener : => A) : ManagedResource[A] = new DefaultManagedResource(opener)
Can someone explain the meaning of [A : Resource : Manifest] ?
Loosely, a parameter is a type, and an argument is an instance. A parameter is an intrinsic property of the procedure, included in its definition. For example, in many languages, a procedure to add two supplied integers together and calculate the sum would need two parameters, one for each integer.
A type parameter, also known as a type variable, is an identifier that specifies a generic type name. The type parameters can be used to declare the return type and act as placeholders for the types of the arguments passed to the generic method, which are known as actual type arguments.
In a generic type or method definition, a type parameter is a placeholder for a specific type that a client specifies when they create an instance of the generic type.
To declare a bounded type parameter, list the type parameter's name, followed by the extends keyword, followed by its upper bound, which in this example is Number . Note that, in this context, extends is used in a general sense to mean either "extends" (as in classes) or "implements" (as in interfaces).
def managed[A : Resource : Manifest](opener : => A) : ManagedResource[A] = new DefaultManagedResource(opener)
means
def managed[A](opener : => A)(implicit r: Resource[A], m: Manifest[A]) : ManagedResource[A] = new DefaultManagedResource(opener)
You can look link text 7.4 Context Bounds and View Bounds for more information.
Using a simpler example to illustrate:
def method[T : Manifest](param : T) : ResultType[T] = ...
The notation T : Manifest
means that there is a context bound. Elsewhere in your program, in scope, must be defined a singleton or value of type Manifest[T]
that's marked as an implicit.
This is achieved by the compiler rewriting the method signature to use a second (implicit) parameter block:
def method[T](param : T)(implicit x$1 : Manifest[T]) : ResultType[T] = ...
As your example illustrates, multiple context bounds can be used in the same method signature. It's also possible to combine them with view bounds.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With