无条件地在Scala中返回字符串

时间:2018-07-25 08:56:03

标签: scala

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

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条件返回结果?

2 个答案:

答案 0 :(得分:3)

您可以将mapgetOrElse结合使用:

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)

答案 1 :(得分:2)

为完整起见,这里使用的是fold而不是map / getOrElse

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