Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why when I unit test do I get coverage points with `final lazy val` but not `final val`?

I have some code (project source available here - https://github.com/natemurthy/testing-final-vals):

object Main extends App {
  final val NAME = "foo"
}

And I'm using ScalaTest and the SBT Coverage plugin to test this code like so:

import org.scalatest.{FlatSpec,Matchers}

class MainTest extends FlatSpec with Matchers {
  it should "have a name" in {
    Main.NAME shouldBe "foo"
  }
}

But for some reason I only get coverage points when I include a lazy modifier in this expression:

enter image description here

enter image description here

Why is this the case?

like image 375
nmurthy Avatar asked Jul 08 '15 06:07

nmurthy


1 Answers

My Guess is that the coverage tool counts executed lines.

final val NAME = "foo"is compiled as a constant inline value in bytecode like private static final in Java. When accessing the variable you just read the value from the bytecode constant. More Info on inlining constant values during compiling

final lazy val NAME = "foo"on the other hand compiles into a lazy construction method since there are no lazy values in the JVM. If you access this variable the lazy construction method is executed. More info on scala lazy value bytecode generation

like image 177
Lukas Eichler Avatar answered Oct 05 '22 22:10

Lukas Eichler