作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
一边琢磨着Predef.scala
的代码我注意到以下几点:
/** A type for which there is always an implicit value.
* @see [[scala.Array$]], method `fallbackCanBuildFrom`
*/
class DummyImplicit
object DummyImplicit {
/** An implicit value yielding a `DummyImplicit`.
* @see [[scala.Array$]], method `fallbackCanBuildFrom`
*/
implicit def dummyImplicit: DummyImplicit = new DummyImplicit
}
有没有人知道为什么会存在这段看似无用的代码?
最佳答案
最终归结为 type erasure (Java 和 Scala 都使用)。
想象一下这段代码:
object Foo {
def foo(p: String) = 1
def foo(p: Int) = 2
def foo(p: Any) = 3
}
object Main extends App {
Foo.foo("1")
}
object Foo {
def foo(ps: String*) = 1
def foo(ps: Int*) = 2
def foo(ps: Any*) = 3
}
object Main extends App {
Foo.foo("1")
}
Main.scala:4: error: double definition:
def foo(ps: Int*): Int at line 3 and
def foo(ps: Any*): Int at line 4
have same type after erasure: (ps: Seq)Int
def foo(ps: Any*) = 3
^
Main.scala:3: error: double definition:
def foo(ps: String*): Int at line 2 and
def foo(ps: Int*): Int at line 3
have same type after erasure: (ps: Seq)Int
def foo(ps: Int*) = 2
^
two errors found
object Foo {
def foo(ps: Object*) = 1
def foo(ps: Object*) = 2
def foo(ps: Object*) = 3
}
object Foo {
def foo(ps: String*) = 1
def foo(ps: Int*)(implicit i: DummyImplicit) = 2
def foo(ps: Any*)(implicit i1: DummyImplicit, i2: DummyImplicit) = 3
}
object Foo extends Object {
def foo(ps: Seq): Int = 1;
def foo(ps: Seq, i: Predef$DummyImplicit): Int = 2;
def foo(ps: Seq, i1: Predef$DummyImplicit, i2: Predef$DummyImplicit): Int = 3;
def <init>(): Foo.type = {
Foo.super.<init>();
()
}
};
object Main extends App {
Foo.foo("1")
Foo.foo(1)
Foo.foo(1.0)
}
Foo.foo(scala.this.Predef.wrapRefArray(Array[String]{"1"}.$asInstanceOf[Array[Object]]()));
Foo.foo(scala.this.Predef.wrapIntArray(Array[Int]{1}), scala.Predef$DummyImplicit.dummyImplicit());
Foo.foo(scala.this.Predef.genericWrapArray(Array[Object]{scala.Double.box(1.0)}), scala.Predef$DummyImplicit.dummyImplicit(), scala.Predef$DummyImplicit.dummyImplicit());
关于scala - 是否使用了 DummyImplicits,如果使用,如何使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34745066/
一边琢磨着Predef.scala的代码我注意到以下几点: /** A type for which there is always an implicit value. * @see [[sca
我是一名优秀的程序员,十分优秀!