1

I'm trying to test an object to check and make sure it is indeed a List. This is in a unit test, and I'm using scalatest assertResult to check like so:

val result: Option[List[String]] = Some(List("A", "List"))
assertResult(classOf[List[String]], "the class should be List of Strings")(result.get.getClass)

This compares result.getClass to classOf[List[String]] and checks equality that way. However, it turns out that result is actually a :: as evidenced by the error message from scalatest:

Expected class scala.collection.immutable.List, but got class scala.collection.immutable.$colon$colon the class should be List of Strings

How can I truly check to see if its a List?

skylerl
  • 4,030
  • 12
  • 41
  • 60
  • 1
    `("a" :: "b" :: Nil).isInstanceOf[List[String]]`? – Andrey Tyukin Feb 20 '19 at 19:36
  • 2
    It's one of those days, I totally forgot that was the way to compare classes... – skylerl Feb 20 '19 at 19:37
  • 1
    @AndreyTyukin I was just going to suggest the same, one problem tough is that `.isInstanceOf[List[String]]` can only check the **List** part, but not the **String** _(I would even write it `.isInstanceOf[List[_]]` just to make the code clearer)_ - if skylerl needs to check also the **String** part, then you may need to use `TypeTag` - However, does not the compiler already checks this?, or your value is actually of type `Option[Any]` ? – Luis Miguel Mejía Suárez Feb 20 '19 at 19:38
  • 1
    @LuisMiguelMejíaSuárez Ah... Yeah, you're of course right. The `isInstanceOf` has the same problem as `classOf[List[String]]` - it will also erase types. I'm not sure what the OP is trying to do, actually. Type checking should usually be left to the type checker at compile time... Maybe it's an XY-problem? – Andrey Tyukin Feb 20 '19 at 19:40
  • 1
    [anInstance mustBe a](http://www.scalatest.org/user_guide/using_matchers#checkingAnObjectsClass) doesn't seem to help with type erasure either. Other suggestions? – Andrey Tyukin Feb 20 '19 at 19:43
  • 1
    If anyone has better suggestions, I think it would be better to add a new answer to the linked duplicate. – Andrey Tyukin Feb 20 '19 at 19:48
  • @AndreyTyukin & skylerl I just posted an answer on the linked question for this specific case. Hope it helps! - BTW, I tried to make something more generic using `TypeTags` but failed miserable. – Luis Miguel Mejía Suárez Feb 20 '19 at 20:02

0 Answers0