这不能按预期工作(因为我试图run
从外部调用私有包Services
):
object Services {
class HelloPrinter {
private[Services] def run = "Hello"
}
}
val obj = new Services.HelloPrinter
但是,令人惊讶的是,这有效:
val obj: {def run: String} = new Services.HelloPrinter
obj.run
我想说,它是编译器中的一个错误,因为由于包可见性规则,HelloPrinter 与结构类型不匹配,所以它根本不应该编译!
这是程序编译但抛出运行时异常(java.lang.NoSuchMethodException
)的情况:
class HelloPrinter {
private[HelloPrinter] def run = "Hello"
}
val obj: {def run: String} = new HelloPrinter
obj.run
这是我缺少的语言功能或规则,还是 Scala 中的合法错误?