scala - 在 Scala 中无条件返回字符串

标签 scala

我有以下变量,我想在没有 if else 条件的情况下打印输出

val students = StudentService.findAllStudents()
val colleges = StudentService.findAllColleges()

我可以使用以下代码在 Scala 中打印输出:
  students.map(student => {
    val college: Option[College] = colleges.find(college => college.collegeId == student.collegeId)
    if(college.isDefined)
      s"${student.firstName} ${student.lastName} (${college.get.name} ${college.get.location})"
    else
      s"${student.firstName} ${student.lastName}"
  }).foreach(println)

有没有什么方法可以在不定义大学时不使用 if else 条件的情况下返回结果?

最佳答案

您可以使用 map结合 getOrElse :

students.map(student => 
    colleges.find(_.collegeId == student.collegeId)
            .map(college => s"${student.firstName} ${student.lastName} (${college.get.name} ${college.get.location})")
            .getOrElse(s"${student.firstName} ${student.lastName}")
).foreach(println)

关于scala - 在 Scala 中无条件返回字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51514794/

相关文章:

scala - 如何使用 GenericRecordBuilder 设置记录数组

scala - 在 Scala 中尝试,反之亦然

scala - 并行运行两个scala函数,5分钟后返回最新值

scala - 为什么 Scala 的 LazyList 元素在计算后显示为未评估?

scala - 直到?处理分块输入。如何?

string - 在 Scala 中将输入流转换为字符串的惯用方法

java - 复杂的加密/解密模型——这有可能吗?

scala - 当我们对 Scala Actor 使用循环而不是 while(true) 时会发生什么?

scala - 根据验证是成功还是失败执行不同副作用的最佳方式

scala - 项目在 IntelliJ 中编译良好,Tomcat 说 java.lang.NoClassDefFoundError : my/package/name/blah