scalafutureprogram-entry-point

Scala Future strange behavior


What's wrong with this code? Why I can see only one output? What returns futureUserByName function? onComplete doesn't work for it as well. It must be just simple Future, but it doesn't work.

import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global

object FeaturesPromises extends App {
  final case class User(name: String)

  def fetchUser(name:String): User = {
    Thread.sleep(1000)
    User(name)
  }

  def futureUserByName(userName: String): Future[User] = Future {
    Thread.sleep(1000)
    fetchUser(userName)
  }

  Future(fetchUser("John")).foreach(println)
  futureUserByName("Jim").foreach(println)
  Thread.sleep(5000)
}

Output>> User(John)

Output by sbt:

User(John)
[success] Total time: 10 s, completed Jul 5, 2024, 11:28:50 PM
[info] 7. Monitoring source files for root/run...
[info]    Press <enter> to interrupt or '?' for more options.
User(Jim)

can anyone explain?


Solution

  • The Application / App always has been and still is completely broken, and

    exists only in a limited form that also does not support command line arguments and will be deprecated in the future.

    Just use a proper @main / object FeaturesPromises { ... def main(...) } instead. This here works just fine (in Scala 3):

    import scala.concurrent.Future
    import scala.concurrent.ExecutionContext.Implicits.global
    
    // object FeaturesPromises extends App {
    final case class User(name: String)
    
    def fetchUser(name:String): User = {
      Thread.sleep(1000)
      User(name)
    }
    
    def futureUserByName(userName: String): Future[User] = Future {
      Thread.sleep(1000)
      fetchUser(userName)
    }
    
    @main def entry(): Unit = {
      Future(fetchUser("John")).foreach(println)
      futureUserByName("Jim").foreach(println)
      Thread.sleep(5000)
    }
    

    In Scala 2, you would have to create a wrapper object with a main method.

    There are no good reasons to use App, just forget that it ever existed.