gpt4 book ai didi

scala - 使用名为 "clone"的隐式类方法编译错误

转载 作者:行者123 更新时间:2023-12-01 11:21:22 25 4
gpt4 key购买 nike

尝试使用名为 clone 的方法创建隐式类时,出现意外编译错误(在 2.11.8 中)。

以下简化用法:

class Foo(val bar: String)

object Foo {
implicit class Enrich(foo: Foo) {
def clone(x: Int, y: Int): Int = x + y
}
}

object Main extends App {
val foo = new Foo("hello")
println(foo.clone(1, 2)) // <- does not compile
}

产生了以下错误:

method clone in class Object cannot be accessed in Foo Access to protected method clone not permitted because prefix type Foo does not conform to object Main where the access take place

但是,我可以手动应用隐式类并成功编译:

println(Foo.Enrich(foo).clone(1, 2))    // <- OK

如果我将方法重命名为其他名称(例如 clone2),代码将按预期进行编译。

我假设这在某种程度上与 java.lang.Cloneable 相关,但该方法不需要参数。

那么这里发生了什么?

最佳答案

这与 Object(或 Scala 中的 AnyRef)拥有一个 protected 方法 clone() 有关。在 Foo 的重载解析中优先。

SI-6760部分讨论了这个问题,尽管 clone 具有相同的签名,而在这种情况下它是不同的。

这感觉像是一个错误(现在打开为 SI-10206 )。当我们用 -Ytyper-debug 扩展 typer 树时,您可以看到它为 def clone(int, int) 找到了一个合适的候选者,但在随后的搜索中失败了:

|-- foo.clone(1, 2) : pt=Unit EXPRmode (site: method main in Main)
| | | | |-- foo.clone BYVALmode-EXPRmode-FUNmode-POLYmode (silent: method main in Main)
| | | | | |-- foo EXPRmode-POLYmode-QUALmode (silent: method main in Main)
| | | | | | \-> foo.type (with underlying type my.awesome.pkg.Foo)
| | | | | [search #1] start `my.awesome.pkg.Foo`, searching for adaptation to pt=foo.type => ?{def clone: ?} (silent: method main in Main) implicits disabled
| | | | | |-- my.awesome.pkg.Foo.Enrich TYPEmode (site: method Enrich in Foo)
| | | | | | \-> my.awesome.pkg.Foo.Enrich
| | | | | |-- Foo TYPEmode (site: value foo in Foo)
| | | | | | \-> my.awesome.pkg.Foo
| | | | | |-- Int TYPEmode (site: method clone in Enrich)
| | | | | | \-> Int
| | | | | |-- Int TYPEmode (site: value x in Enrich)
| | | | | | \-> Int
| | | | | |-- Int TYPEmode (site: value y in Enrich)
| | | | | | \-> Int
| | | | | [search #1] considering pkg.this.Foo.Enrich
| | | | | |-- pkg.this.Foo.Enrich BYVALmode-EXPRmode-FUNmode-POLYmode (silent: method main in Main) implicits disabled
| | | | | | \-> (foo: my.awesome.pkg.Foo)my.awesome.pkg.Foo.Enrich
| | | | | [search #1] success inferred value of type foo.type => ?{def clone: ?} is SearchResult(pkg.this.Foo.Enrich, )
| | | | | [search #2] start `my.awesome.pkg.Foo`, searching for adaptation to pt=(=> foo.type) => ?{def clone: ?} (silent: method main in Main) implicits disabled
| | | | | \-> <error>
Main.scala:6: error: method clone in class Object cannot be accessed in my.awesome.pkg.Foo
Access to protected method clone not permitted because
prefix type my.awesome.pkg.Foo does not conform to
object Main in package pkg where the access take place
foo.clone(1, 2) // <- does not compile

编辑

这确实在 2.10.6 下编译

关于scala - 使用名为 "clone"的隐式类方法编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42423441/

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