Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

":" in type parameter

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] ?

like image 500
xiefei Avatar asked Sep 26 '10 14:09

xiefei


People also ask

What is a parameter type?

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.

What is Java type parameter?

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.

What is a type parameter in C#?

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.

How do you declare a type parameter?

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).


2 Answers

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.

like image 142
Eastsun Avatar answered Oct 02 '22 08:10

Eastsun


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.

like image 29
Kevin Wright Avatar answered Oct 02 '22 08:10

Kevin Wright