Home > database >  cannot access value in companion object
cannot access value in companion object

Time:07-20

I have a companion object which looks as follows:

case class ShowItemMessageStreamMock[A](item: A)

object ShowItemMessageStreamMock extends ShowItemMessageStream
{
    def addItemToMessageStream[A](view: A): Unit =
    {
        new ShowItemMessageStreamMock(view)
    }
}

and I have a assertion, which looks like this:

assert(ShowItemMessageStreamMock.item.nonEmpty)

( just pretend, that the addItemToMessageStream method ran and item has a value in it )

but when I hover over the item in the assertion, I get this error message:

value item is not a member of object ShowItemMessageStreamMock

I thought, I can access all values of each companion?

So my question is, why can´t I acces this item value?

CodePudding user response:

So my question is, why can´t I acces this item value?

Because it doesn't exist. The companion object ShowItemMessageStreamMock does not have an item member.

You could put the assertion inside the case class like this:

case class ShowItemMessageStreamMock[A](item: A) {
   assert(item.nonEmpty)
}

Of course this won't work because item is of unknown type and may not have a nonEmpty method, but at least you are checking the right value! And there are better ways of enforcing this than using an assertion.

But the following code is also messed up because it creates an object and then discards all references to it:

def addItemToMessageStream[A](view: A): Unit =
{
    new ShowItemMessageStreamMock(view)
}

It's probably worth taking a step back and explaining what it is you are actually trying to do.

  • Related