joesan
joesan

Reputation: 15435

Scala Expose a Case class nested in a trait

I have a trait:

MyTrait {

  ...
  ...

  case class MyCaseClass(...)
}

object MyTrait {
  case class SomeOtherCaseClass(...)
}

For some of my tests, I would need to expose the MyCaseClass(...). How can I import this in my tests?

Upvotes: 1

Views: 1095

Answers (3)

Daenyth
Daenyth

Reputation: 37461

This probably doesn't do what you want it to do. Each instance will have its own type of MyCaseClass. in other words:

val a = new MyTrait {}
val b = new MyTrait {}
a.MyCaseClass.getClass != b.MyCaseClass.getClass

The general way to do this is either to put it top level:

case class MyCaseClass( ... )
trait MyTrait { ... }

Or if you want it more tightly scoped, put it in the companion object

object MyTrait {
  case class MyCaseClass(...)
}
trait MyTrait { ... }

Upvotes: 4

Vikas Pandya
Vikas Pandya

Reputation: 1988

trait Mytrait{
  case class MyCaseClass(t:String)
}
object Mytrait extends Mytrait

then you can

import Mytrait._

and call MyCaseClass("t")

Upvotes: 0

joesan
joesan

Reputation: 15435

I ended up doing what I did not want. My test class extends this trait that contains the case class in question!

Upvotes: 0

Related Questions