在Scala中,如何为Java定义的类定义伴随对象? [英] In Scala, how can I define a companion object for a class defined in Java?

查看:86
本文介绍了在Scala中,如何为Java定义的类定义伴随对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将隐式转换添加到由建模工具生成的Java类中.因此,我想将它们添加到这些类的伴随对象中,以便编译器自动找到它们.但是我不能将它们添加到单独的文件中,因为同伴必须在同一文件中定义.我对此有什么能做的吗?

I'd like to add implicit conversions to Java classes generated by a modeling tool. So I want to add them to the companion object of those classes, so that the compiler automatically finds them. But I cannot add them in a separate file, because the companion has to be defined in the same file. Is there anything I can do about this?

当然,我可以在另一个对象中定义所有隐式转换,然后将其带入范围,但这需要额外的导入.还有其他解决方案吗?

Of course, I can define all my implicit conversions in another object and then bring it into scope, but this requires an extra import. Any other solution?

推荐答案

现在使用Scala编译器,只能通过将同伴对象放入同一文件中来定义同伴对象.最好的办法是使用具有相同程序包和名称的非伴侣对象,并执行额外的导入操作.

With the Scala compiler as it stands now there is no way to define companion objects other than by putting them in the same file. The best you can do is a non-companion object with the same package and name and an extra import.

如果您想找到一种在不破坏封装的前提下创建事后陪伴的好方法,请发布在

If you can think of a good way to create post-hoc companionship without breaking assumptions about encapsulation please come post on http://groups.google.com/group/scala-debate because it would clearly be a very useful feature.

这篇关于在Scala中,如何为Java定义的类定义伴随对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆