展平定義為:
override def flatten[B](implicit toIterableOnce: A => IterableOnce[B])
我的代碼是:
val myList = List(1,2,3)
println(myList.map(x => List(x, 2*x)).flatten)
因此,如果我理解正確,當我呼叫 flatten 時,我需要在某處定義一個隱式函式,該函式將 List[Int] 作為輸入并回傳 IterableOnce[Int]。
我還沒有定義任何這樣的函式并且代碼作業正常,所以在某處找到了隱式。我怎樣才能找到它的確切定義?我在 Predef 中期待它,但似乎它不存在。
uj5u.com熱心網友回復:
如果你這樣做
// libraryDependencies = scalaOrganization.value % "scala-reflect" % scalaVersion.value
import scala.reflect.runtime.universe.reify
println(reify{ myList.map(x => List(x, 2*x)).flatten }.tree)
你會看到的
App.this.myList.map(((x) => `package`.List.apply(x, 2.$times(x)))).flatten(Predef.$conforms)
所以含蓄toIterableOnce: A => IterableOnce[B]的是Predef.$conforms(你是對的,它在Predef)
https://github.com/scala/scala/blob/2.13.x/src/library/scala/Predef.scala#L510
/** An implicit of type `A => A` is available for all `A` because it can always
* be implemented using the identity function. This also means that an
* implicit of type `A => B` is always available when `A <: B`, because
* `(A => A) <: (A => B)`.
*/
// $ to avoid accidental shadowing (e.g. scala/bug#7788)
implicit def $conforms[A]: A => A = <:<.refl
的確,List[Int] <: IterableOnce[Int]
implicitly[List[Int] <:< IterableOnce[Int]] // compiles
implicitly[List[Int] => IterableOnce[Int]] // compiles
了解如何除錯隱式很有用:
在 scala 2 或 3 中,是否可以在運行時除錯隱式決議程序?
uj5u.com熱心網友回復:
FWIW,如果使用 Scala 2,您還可以使用-Xprint:typer標志運行您的程式scalaor scalac,您將看到編譯器在您的程式中插入的所有隱式:
println(myList.map(x => List(x, 2*x)).flatten)
被翻譯成:
scala.Predef.println(Main.this.myList.map[List[Int]](((x: Int) =>
scala.`package`.List.apply[Int](x, 2.*(x))))
.flatten[Any](scala.Predef.$conforms[List[Int]]))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/508562.html
上一篇:TrinoUDF插件:哪個是對應的Java型別來映射(字串,字串)
下一篇:sbt-protoc錯誤檔案不在使用--proto_path(或-I)指定的任何路徑中。您必須指定包含此檔案的--proto_path
