我可以給你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