Search code examples
scalacompanion-objecttype-alias

Avoid duplicate type alias in Scala class and companion object


I'm a newbie in Scala, and I have a Scala program with a class and a companion object, and I want to use a type alias that is used :

  1. To define the methods of the class.
  2. Also I want to use the alias outside the class. For that I find useful to define the alias in the companion object, to import the alias from the companion object. I also have some implicits defined in the companion object so this is just natural.

The concrete code is available at https://github.com/juanrh/Surus/blob/1cfd55ed49c4d1b22e53babe07bcf44fd74e3072/src/main/scala/org/surus/spark/SurusRDDFunctions.scala, the type alias is PMMLPrediction and the class is SurusRDDFunctions. Currently the code works but I have defined the alias both in the class and the companion, which is not very nice. If I remove the definition of the alias in the class then the class is not able to find it, which seems weird. So I think I'm probably doing something wrong, any ideas?

Thanks a lot in advance for your help!

Greetings,

Juan


Solution

  • Given the companion object

    object Example {
      type MyString = String
    }
    

    You can access the type directly through to the companion object

    class Example (val name: Example.MyString) { }
    

    Or by importing it from the companion object

    class Example {
      import Example._
    
      val name: MyString = "example"
    }