2

I have a Scalatest with the following structure which is emasculated within a class

var dataHolder: Holder // some lazy initialization here? 


def runTest(filePath: String): Unit = {

       //Test 1
        it should "load the data holder" in {
            loadHolder(filePath)
        }

        //Test 2
        it should "varify the holder is correct" in {
            checkHolder(dataHolder)
        }
  }

Test 1 and 2 are both needs dataHolder variable, which is generated by function loadHolder( String ), the loading Holder is I/O and computation intense, therefore I don't want to do it again in Test 2.

I'm looking for a way that both tests can see the variable and the first one is responsible to initialize it, how can I do it? Is there lazy-initialization in Scala?

SLN
  • 4,772
  • 2
  • 38
  • 79
  • 1
    [duplicate of duplicate](https://stackoverflow.com/questions/4095170/scala-lazy-values-performance-penalty-threadsafe)? Or of [this here](https://stackoverflow.com/questions/3041253/whats-the-hidden-cost-of-scalas-lazy-val)? Or [this](https://stackoverflow.com/questions/7484928/what-does-a-lazy-val-do?noredirect=1&lq=1)? – Andrey Tyukin May 22 '19 at 15:05
  • If you need to share _(mutable)_ state across many tests, and if that state require intensive IO. I would double check the design. – Luis Miguel Mejía Suárez May 22 '19 at 15:08
  • No, don't think it works for me. I just want to declare the type and initialize it in the test function – SLN May 22 '19 at 15:08
  • 2
    Just `var dataHolder: Holder = _ // or null.` and, if `loadHolder` returns the holder, `dataholder = loadHolder(filePath)` in your first test. – Luis Miguel Mejía Suárez May 22 '19 at 15:22

0 Answers0