Why does this scala by-name parameter behave strangely

OK, the question may not say much, but here's the deal: I study scala and decided to make the utility class "FuncThread" using a method that receives the by-name parameter function (I think it was called because it is a function, but without a list of parameters) , and then starts the thread with which, in turn, performs the passed function, I wrote this class as follows:

class FuncThread
{
   def runInThread( func: => Unit)
   {
     val thread = new Thread(new Runnable()
     {
        def run()
        {
          func
        }
     }

     thread.start()
   }
}

Then I wrote a junit test as follows:

@Test
def weirdBehaivorTest()
{
  var executed = false
  val util = new FuncThread()
  util.runInThread
  {
    executed = true
  }

  //the next line makes the test pass....
  //val nonSense : () => Unit  = () => { Console println "???" }

  assertTrue(executed)
}

If I uncomment the second commented line, the test passes, but if it remains commented, the test fails, is this the correct behavior? how and when are the name parameter functions performed?

I know that scala has a member library, but I wanted to try this, since I always wanted to do this in Java

+3
2

? runInThread , "" , true. , ( ), , "execute" true

+7

, ( Scala 2.8)

import scala.actors.Futures._

future{
    executed = true
}

, , , .

import scala.actors.Futures._

//forks off expensive calculation
val expensiveToCalculateNumber:Future[Int] = future{
    bigExpensiveCalculation()  
}

// do a lot of other stuff

//print out the result of the expensive calculation if it ready, otherwise wait until it is
println( expensiveToCalculateNumber());
+4

Source: https://habr.com/ru/post/1771945/


All Articles