Omid
Omid

Reputation: 1989

companion objects for type alias

I have the following case class with a companion object:

case class A(boo:String)
object A{
 def foo(x:a) = ...
}

And I have the following type alias in my package object:

type NewA = A

I want all the method in A companion object to be in the companion object of NewA. I know one way to do it but it's not nice:

object NewA{
  val instance = A
}
NewA.instance.foo(...)

is there any way to write it in a better way?

Upvotes: 2

Views: 1836

Answers (2)

Sean Vieira
Sean Vieira

Reputation: 159955

Simply add a val to your package object that references A:

package object your_package {
  type NewA = A
  val NewA = A
}

Then you can use NewA from your_package just like you would use A:

import your_package.NewA

NewA.foo(...)

Upvotes: 11

Till Rohrmann
Till Rohrmann

Reputation: 13346

You could use implicit conversions to convert NewA into A

implicit convertNewA2A(newA: NewA.type) = A

NewA.foo(...)

Alternatively, you could factor the methods of A out into a trait from which both companion objects extend.

Upvotes: 0

Related Questions