You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Scala中通过链式调用Futures计算用户总分的实现求助

Implementing getTotalScore for Async Score Calculation

Hey there! Let's tackle this getTotalScore implementation step by step. Since all our data retrieval methods return Futures, we need to properly compose these asynchronous operations to keep things efficient and avoid unnecessary blocking.

Core Logic Breakdown

Here's what we need to do for each user in the class:

  1. Fetch all their subjects, filtering only those marked includeForTotal = true
  2. Sum up the scores for those eligible subjects
  3. Add the user's bonus score to that sum
  4. Wrap everything into a UserScore instance, then collect all results for the class

The Implementation

We can use Scala's for comprehensions to make the async flow read like synchronous code, and Future.traverse to handle converting a sequence of users into a sequence of their computed scores (wrapped in a single Future):

def getTotalScore(classID: Int): Future[Seq[UserScore]] = {
  // First, get all users in the target class
  getUsers(classID).flatMap { users =>
    // Traverse each user to compute their total score asynchronously
    Future.traverse(users) { user =>
      val userId = user.id
      for {
        // Fetch the user's subjects and filter those that count towards the total
        subjects <- getSubjects(userId)
        includedSubjects = subjects.filter(_.includeForTotal)
        
        // Fetch scores for all included subjects, then sum them up
        subjectScores <- Future.sequence(includedSubjects.map(subject => getScore(subject.id, userId)))
        subjectTotal = subjectScores.sum
        
        // Fetch the bonus score and calculate the final total
        bonus <- getBonusScore(userId)
        finalTotal = subjectTotal + bonus
      } yield UserScore(userId, finalTotal)
    }
  }
}

Key Details Explained

  • Future.traverse: This is a handy shortcut that combines map and Future.sequence—it takes a Seq[A] and a function A => Future[B], then returns a Future[Seq[B]]. Perfect for processing multiple users in parallel.
  • for Comprehension: Lets us chain multiple Future operations sequentially without nested flatMap calls, making the code much easier to read.
  • Future.sequence: Converts a Seq[Future[Int]] (one future per subject score) into a Future[Seq[Int]], so we can safely sum all the scores once they're all available.

Expected Output

When you run the code, you'll see:

class1: List(UserScore(1,90), UserScore(2,95))
class2: List(UserScore(1,90), UserScore(2,95))
  • User 1: 60 (subject 1 score) + 30 (bonus) = 90
  • User 2:75 (subject 1 score) +20 (bonus) =95

内容的提问来源于stack exchange,提问作者Yatheesha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 07:32:18