- Good example of implicit parameter in Scala?
- max(x : Int,y : Int) : Int
- max(5,6);
- max(x:5,y:6);
- x = 5;
- y = 6;
- max()
- max() : Int
- {
- global x : Int;
- global y : Int;
- ...
- }
- def max[T <% Ordered[T]](a: T, b: T): T = if (a < b) b else a
- def max[T](a: T, b: T)(implicit $ev1: Function1[T, Ordered[T]]): T = if ($ev1(a) < b) b else a
- def max[T](a: T, b: T)(implicit $ev1: Ordering[T]): T = if ($ev1.lt(a, b)) b else a
- // latter followed by the syntactic sugar
- def max[T: Ordering](a: T, b: T): T = if (implicitly[Ordering[T]].lt(a, b)) b else a
- new Array[Int](size)
- def f[T](size: Int) = new Array[T](size) // won't compile!
- def f[T: ClassManifest](size: Int) = new Array[T](size)
- Manifest // Provides reflection on a type
- ClassManifest // Provides reflection on a type after erasure
- Ordering // Total ordering of elements
- Numeric // Basic arithmetic of elements
- CanBuildFrom // Collection creation
- def withTransaction(f: Transaction => Unit) = {
- val txn = new Transaction
- try { f(txn); txn.commit() }
- catch { case ex => txn.rollback(); throw ex }
- }
- withTransaction { txn =>
- op1(data)(txn)
- op2(data)(txn)
- op3(data)(txn)
- }
- withTransaction { implicit txn =>
- op1(data)
- op2(data)
- op3(data)
- }
- def flatten[B](implicit ev: A <:< Option[B]): Option[B]
- scala> Option(Option(2)).flatten // compiles
- res0: Option[Int] = Some(2)
- scala> Option(2).flatten // does not compile!
- <console>:8: error: Cannot prove that Int <:< Option[B].
- Option(2).flatten // does not compile!
- ^
- trait ScalaActorRef { this: ActorRef =>
- ...
- def !(message: Any)(implicit sender: ActorRef = null): Unit
- ...
- }
- trait Actor {
- ...
- implicit val self = context.self
- ...
- }
- someOtherActor ! SomeMessage
- someOtherActor.!(SomeMessage)(self)
- someOtherActor.!(SomeMessage)(null)
- someOtherActor.!(SomeMessage)(anotherActorAltogether)
- def max[B >: A](implicit cmp: Ordering[B]) : A
- implicit val num = 2
- implicit val item = "Orange"
- def shopping(implicit num: Int, item: String) = {
- "I’m buying "+num+" "+item+(if(num==1) "." else "s.")
- }
- scala> shopping
- res: java.lang.String = I’m buying 2 Oranges.
- def map[B, That](f: (A) ⇒ B)(implicit bf: CanBuildFrom[GenSeq[A], B, That]): That