简体   繁体   English

使用Scala的Java中的C#扩展方法

[英]C# extension methods in Java using Scala

I need to create some extension methods in my Java code. 我需要在Java代码中创建一些扩展方法。 I've read some posts here in SO and people suggest XTend or Scala in order to achieve this. 我已经阅读了SO上的一些文章,人们建议使用XTend或Scala来实现这一目标。

Now, my question would be.. if i write kind of an Adapter layer in Scala (adding there my extension methods) and then using that project as a dependency for my own Java project, are those extended methods available for me to use, or they are defined just for the 'scope of Scala project' and then the JVM output cannot provide those new methods to the other project using it? 现在,我的问题是..如果我在Scala中编写某种Adapter层(在其中添加扩展方法),然后将该项目用作我自己的Java项目的依赖项,那么这些扩展方法是否可供我使用,或者它们只是为“ Scala项目范围”定义的,然后JVM输出无法使用这些新方法向其他项目提供这些新方法吗?

EDIT: What i need to do is to extend a full hierarchy of classes in a given library and give some new functionality. 编辑:我需要做的是在给定的库中扩展类的完整层次结构,并提供一些新功能。 As for Java's first approach I should extend every class in that hierarchy creating my own hierarchy of extended classes adding the new method there. 至于Java的第一种方法,我应该扩展该层次结构中的每个类,以创建自己的扩展类层次结构,并在其中添加新方法。 I would like to avoid this and give the final user the sense of native functionality in the original hierarchy. 我想避免这种情况,并让最终用户了解原始层次结构中的本机功能。

Regards. 问候。

As mentioned above in the comments, it is very close to C# but not exactly there because of the type erasure. 如上面的注释中所述,它与C#非常接近,但由于类型擦除而与C#并不完全相同。 For example, this works fine: 例如,这可以正常工作:

object myLibExtensions {
    implicit class TypeXExtension( val obj: TypeX ) extends AnyRef {
        def myCustomFunction( a: String ): String = {
            obj.someMethod(a)
        }
    }
}

It will act somewhat similar to C# extension methods, ie create static method wrappers in reasonable cases ( but not always ). 它的作用类似于C#扩展方法,即在合理的情况下( 但并非总是 )创建静态方法包装。

The only thing I am missing in Scala is that you can't (or at least I couldn't figure out how to) return the values of the types being extended. 我在Scala中唯一缺少的是您无法(或者至少我无法弄清楚如何)返回被扩展类型的值。 For example, assume I want to have something like an extension method "withMeta" that works as follows: 例如,假设我想拥有一个扩展方法“ withMeta”,其工作方式如下:

class TypeY extends TypeX { def methodOfY(...) ...}

var y: TypeY = ....

y.withMeta(...).methodOfY(...)

The following didn't work for me: 以下对我不起作用:

object myLibExtensions {
    private val something = ....
    implicit class Extension[T<:TypeX]( val obj: T ) extends AnyRef {
        def withMeta( meta: Meta[T] ): T = {
            something.associateMeta(obj,meta)
            val
        }
    }
} 

... because T is being erased to TypeX. ...因为T正在被擦除到TypeX。 So effectively you will have to write extensions for all specific leaf classes of the hierarchy in this case, which is sad. 因此,在这种情况下,您必须有效地为层次结构的所有特定叶类编写扩展,这很可悲。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM