我有以下变量,我想在没有其他条件的情况下打印输出
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条件返回结果?
答案 0 :(得分:3)
您可以将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)
答案 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)