helloworld
helloworld

Reputation: 137

cannot access value in companion object

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?

Upvotes: 0

Views: 149

Answers (1)

Tim
Tim

Reputation: 27356

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.

Upvotes: 1

Related Questions