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

后端 未结 2 1170
没有蜡笔的小新
没有蜡笔的小新 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条回答
  •  -上瘾入骨i
    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)

提交回复
热议问题