Type aliasing Java classes with statics

大兔子大兔子 提交于 2021-02-07 00:27:06

问题


Suppose MyClass is a class defined in Java, and has many static as well as non-static members. I tried to alias this class (and associated companion object) in a Scala object MyObject as shown below:

object MyObject {
  import javastuff._
  type MyAlias = MyClass
  val MyAlias = MyClass
}

Scalac complains:

error: object MyClass is not a value
val MyAlias = MyClass

How do I work around this? Thanks.


回答1:


Although this works in pure Scala for a class + companion object, it's not possible with Java's static methods, as these don't belong to any interface.

Scala could, in theory, create an object containing delegates to all the static methods of some class, but it doesn't do this currently. It's also possible to write a compiler plugin for this if you feel comfortable writing plugins.

Failing that, you'll either have to create an object full of delegates yourself, or just cherry-pick a few methods and pass them around as functions.




回答2:


it's not possible with Java's static methods, as these don't belong to any interface.

Update 5 years later: PR 5131 mentions:

We used to disable generation of static forwarders when a object had a trait as a companion, as one could not add methods with bodies to an interface in JVM 6.

The JVM lifted this restriction to support default methods in interfaces, so we can lift the restriction on static forwarders, too.

Fixes scala-dev issue 59

See commit 41c9a17 by Jason Zaugg (retronym).



来源:https://stackoverflow.com/questions/4943256/type-aliasing-java-classes-with-statics

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!