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

后端 未结 2 1171
没有蜡笔的小新
没有蜡笔的小新 2020-12-06 17:51

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 auto

相关标签:
2条回答
  • 2020-12-06 18:14

    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.

    0 讨论(0)
  • 2020-12-06 18:15

    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)

    0 讨论(0)
提交回复
热议问题