我尝试使用不同的排序顺序为我的电影列表创建输出(取决于我输入的参数),但参数不起作用。 错误:值排序不是Scala.Movie的成员
def printResult(list: List[Movie], sorting : String) = {
val movieList = list.filter(element => element.isInstanceOf[Movie])
if (movieList.length > 0)
{
val resultSize = chooseResultSize()
val sizedList = movieList.filter(element => movieList.indexOf(element) < resultSize)
val formtLength = sizedList.map(_.title.length).max + 9
val printPattern = "%-" + formtLength + "s"
println(s"\n$printPattern %-9s %-9s %-9s".format("Title", "Year", "Votes", "Rating"))
for (movie <- ((for (film <- sizedList) yield film.asInstanceOf[Movie]).sortBy(_.sorting).reverse)) println(s"$printPattern %-9s %-9d %-9.1f".format(movie.title.trim, movie.year, movie.votes, movie.rating))
}
else println("Sorry - no matches found!")
}
答案 0 :(得分:0)
sortBy
函数会等待函数(Scala.Movie) => B
。因此,您不能只传递一个String值来指示您要排序的字段,您必须传递一个函数。
val movies = for (movie <- for (film <- sizedList) yield film.asInstanceOf[Movie]) yield movie
val sortedMovies = (sorting match {
case "byYear" => movies.sortBy(_.year)
case "byVotes" => movies.sortBy(_.votes)
case _ => movies.sortBy(_.title)
}).reverse
sortedMovies foreach(movie => println(s"$printPattern %-9s %-9d %-9.1f".format(movie.title.trim, movie.year, movie.votes, movie.rating)))