def managed[A : Resource : Manifest](opener : => A) : ManagedResource[A] = new DefaultManagedResource(opener)
meansdef managed[A](opener : => A)(implicit r: Resource[A], m: Manifest[A]) : ManagedResource[A] = new DefaultManagedResource(opener)
----
Using a simpler example to illustrate:
def method[T : Manifest](param : T) : ResultType[T] = ...
The notation
This is achieved by the compiler rewriting the method signature to use a
second (implicit) parameter block: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.def method[T](param : T)(implicit x$1 : Manifest[T]) : ResultType[T] = ...
reference:
http://stackoverflow.com/questions/3798296/in-type-parameter
==========================================================================
http://docs.scala-lang.org/tutorials/tour/implicit-parameters.html
http://docs.scala-lang.org/sips/completed/implicit-classes.html (implicit classes)
In the following example we define a methodsum
which computes the sum of a list of elements using the monoid’sadd
andunit
operations. Please note that implicit values can not be top-level, they have to be members of a template.
abstract class SemiGroup[A] {
def add(x: A, y: A): A
}
abstract class Monoid[A] extends SemiGroup[A] {
def unit: A
}
object ImplicitTest extends App {
implicit object StringMonoid extends Monoid[String] {
def add(x: String, y: String): String = x concat y
def unit: String = ""
}
implicit object IntMonoid extends Monoid[Int] {
def add(x: Int, y: Int): Int = x + y
def unit: Int = 0
}
def sum[A](xs: List[A])(implicit m: Monoid[A]): A =
if (xs.isEmpty) m.unit
else m.add(xs.head, sum(xs.tail))
println(sum(List(1, 2, 3)))
println(sum(List("a", "b", "c")))
}
Here is the output of the Scala program:
6
abc
No comments:
Post a Comment