扁平化被定义为:
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时,我需要在某个地方定义一个隐式函数,这个函数以ListInt作为输入并返回IterableOnceInt。
我还没有定义任何这样的函数,而且代码工作得很好,所以在某个地方可以找到隐式函数。我怎样才能找到它的确切定义?我在Predef料到了,但似乎不在那里。
发布于 2022-09-10 11:40:00
如果你这样做了
// 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知道如何进行调试是很有用的:
In scala 2 or 3, is it possible to debug implicit resolution process in runtime?
发布于 2022-09-10 17:19:06
FWIW,如果使用Scala 2,也可以使用-Xprint:typer标志使用scala或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://stackoverflow.com/questions/73671331
复制相似问题