gpt4 book ai didi

scala - 为什么我们需要在 Scala 中使用隐式参数?

转载 作者:行者123 更新时间:2023-12-04 15:57:12 24 4
gpt4 key购买 nike

我是 Scala 的新手,今天当我遇到这个 akka source code我不解:

def traverse[A, B](in: JIterable[A], fn: JFunc[A, Future[B]], 
executor: ExecutionContext): Future[JIterable[B]] = {
implicit val d = executor
scala.collection.JavaConversions.iterableAsScalaIterable(in).foldLeft(
Future(new JLinkedList[B]())) { (fr, a) ⇒
val fb = fn(a)
for (r ← fr; b ← fb) yield { r add b; r }
}
}

为什么故意使用隐式参数编写代码?为什么不能写成:
scala.collection.JavaConversions.iterableAsScalaIterable(in).foldLeft(
Future(new JLinkedList[B](),executor))

不声明新的隐式变量 d ?这样做有什么好处吗?现在我只发现隐式增加了代码的歧义。

最佳答案

我可以给你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)它允许您使用通用方法创建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 个 future 怎么办:
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 .

关于“代码的歧义”:

您不必使用隐式,或者您可以显式指定所有参数。它有时看起来很丑(参见 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 - 为什么我们需要在 Scala 中使用隐式参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13812352/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com