2

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?

2 Answers 2

11

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(...)
1
  • It works in most contexts but there is no implicit scope in val NewA
    – tribbloid
    Feb 4, 2019 at 20:32
0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.