我可以给你3个理由。
1)它隐藏了样板代码。
那种让一些列表:
import math.Ordering
List(1, 2, 3).sorted(Ordering.Int) // Fine. I can tell compiler how to sort ints
List("a", "b", "c").sorted(Ordering.String) // .. and strings.
List(1 -> "a", 2 -> "b", 3 -> "c").sorted(Ordering.Tuple2(Ordering.Int, Ordering.String)) // Not so fine...
使用隐式参数:
List(1, 2, 3).sorted // Compiller knows how to sort ints
List(1 -> "a", 2 -> "b", 3 -> "c").sorted // ... and some other types
2)alows您创建泛型方法API:
scala> (70 to 75).map{ _.toChar }
res0: scala.collection.immutable.IndexedSeq[Char] = Vector(F, G, H, I, J, K)
scala> (70 to 75).map{ _.toChar }(collection.breakOut): String // You can change default behaviour.
res1: String = FGHIJK
3)它允许你要专注于真正重要的事情:
Future(new JLinkedList[B]())(executor) // meters: what to do - `new JLinkedList[B]()`. don't: how to do - `executor`
这不是那么糟糕,但如果你需要2个期货:
val f1 = Future(1)(executor)
val f2 = Future(2)(executor) // You have to specify the same executor every time.
隐式创建的所有行动 “背景”:
implicit val d = executor // All `Future` in this scope will be created with this executor.
val f1 = Future(1)
val f2 = Future(2)
3.5)隐参数允许类型级编程。见shapeless。
关于“代码的不确定性”:
您不必使用implicits,或者你可以显式指定所有参数。它有时看起来很丑(参见sorted
例子),但是你可以做到。
如果你不能找到其隐含变量作为参数,你可以问编译:
>echo object Test { List((1, "a")).sorted } > test.scala
>scalac -Xprint:typer test.scala
你会发现在输出math.this.Ordering.Tuple2[Int, java.lang.String](math.this.Ordering.Int, math.this.Ordering.String)
。
隐含是强大的,但如果它将语言变成一种程序员的方言,它将很难理解,特别是当你需要更多的人编写数千个代码时。 scala是否有创建含义的规则? – CharlieQ
看看[typeclass](http://stackoverflow.com/a/5426131/406435)。它允许你在没有继承的情况下添加行为。这是推荐使用隐式参数。你的问题中的“未来”使用某种“背景”。创建这样的“上下文”是隐式参数的常见用法。 – senia
谢谢,这个链接很有用 – CharlieQ