Search code examples
scalascalatestscalacheck

How to easily generate longs with scalacheck?


I tried

  val arbLong: Gen[Long] = {
    Gen.frequency((20, Arbitrary.arbLong), (20, null)).sample.get.arbitrary
  }


  "arbLong" should "be able to generate null values" in {
    forAll(arbLong) { (generatedLong: Long) =>
      println(generatedLong)
    }

  }

so it does generate a null for longs, however I get NullPointerException most probably because of Long cannot hold null what is the proper way to use an arbitrary long generator which includes nulls?


Solution

  • Scala's Long cannot be null (Pass null to a method expects Long). If you want to represent Longs which may or may not be present then use either java.lang.Long:

    val arbLong: Gen[java.lang.Long] = {
      Gen.frequency((20, Arbitrary.arbLong), (20, null)).sample.get.arbitrary
    }
    

    or Option[Long] (see Generate Option[T] in ScalaCheck).