Skip to content

Type of package #18109

Closed
Closed
@prolativ

Description

@prolativ

Compiler version

3.3.0, 3.3.2-RC1-bin-20230629-90c59bd-NIGHTLY

Minimized code

package foo {}

package bar {
  object Test {
    def qux[A] = 123
    def main(args: Array[String]): Unit = {
      val y = qux[foo.type]
      val x = valueOf[foo.type]
    }
  }
}

Compilation output

Warning: mocking up superclass for module class foo

Runtime output

Exception in thread "main" java.lang.NoClassDefFoundError: foo
        at bar.Test$.main(PackageType.scala:8)
        at bar.Test.main(PackageType.scala)
Caused by: java.lang.ClassNotFoundException: foo
        at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:418)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:352)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:351)
        ... 2 more

Expectation

Should it be possible to refer to the type of a package at all? It seems harmless if one treats it as a phantom type (the snippet doesn't crash at runtime if val x = valueOf[foo.type] gets commented out but still leaving the invocation of qux[foo.type]). On the other hand the compiler sees such types as subtypes of Singleton and tries to provide a given instance of ValueOf for them.
Neither scala 3.2.2 nor 2.13.11 allow referring to types of packages as shown below:

  • scala 3.2.2
[error] ./PackageType.scala:7:19
[error] package foo is not a value
[error]       val y = qux[foo.type]
[error]                   ^^^
[error] ./PackageType.scala:8:23
[error] package foo is not a value
[error]       val x = valueOf[foo.type]
[error]                       ^^^
  • scala 2.13.11
[error] ./PackageType.scala:7:15
[error] type arguments [foo.type] do not conform to method qux's type parameter bounds [A]
[error]       val y = qux[foo.type]
[error]               ^^^^^^^^^^^^^
[error] ./PackageType.scala:8:15
[error] type arguments [foo.type] do not conform to method valueOf's type parameter bounds [T]
[error]       val x = valueOf[foo.type]
[error]               ^^^^^^^^^^^^^^^^^

@odersky should we keep the possibility to refer to package types but make it safe at runtime or should this be disabled? Would allowing such references actually require a change in the language specification (introduced by a SIP)?

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions