使用静态类型别名 Java 类 [英] Type aliasing Java classes with statics
问题描述
假设 MyClass
是一个用 Java 定义的类,并且有许多静态和非静态成员.我试图在 Scala 对象 MyObject
中为这个类(和相关联的对象)取别名,如下所示:
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 抱怨:
error: object MyClass is not a value
val MyAlias = MyClass
我该如何解决这个问题?谢谢.
How do I work around this? Thanks.
推荐答案
虽然这在纯 Scala 中适用于类 + 伴生对象,但在 Java 的静态方法中是不可能的,因为这些不属于任何接口.
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 可以,理论上,创建一个包含某个类的所有静态方法的委托的对象,但它目前不这样做.如果您愿意编写插件,也可以为此编写编译器插件.
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.
这篇关于使用静态类型别名 Java 类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!