In Scala, how can I define a companion object for a class defined in Java?

廉价感情. 提交于 2019-11-28 00:58:29

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.

You can define your own companion object of course, which I often do in my own project-specific Predef-like arrangement. For example:

object domain {

  type TimeUnit = java.util.concurrent.TimeUnit
  object TimeUnit {
    def valueOf(s : String) = java.util.concurrent.TimeUnit.valueOf(str)
    val Millis = java.util.concurrent.TimeUnit.MILLISECONDS
    //etc
  }

Then this can be used:

import my.domain._
val tu : TimeUnit = TimeUnit.valueOf("MILLISECONDS")

But your domain.TimeUnit is a module (i.e. scala object)

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