列表中最长的单词

Cod*_*er0 4 scala list

我有一个带字符串的列表,我想打印出最长的字符串

我已经尝试过该reduceLeft选项,但无论何时我应用它都会返回此错误:

type mismatch; found:String required:Ordering[?]
Run Code Online (Sandbox Code Playgroud)

以下是在第二行中抛出异常的代码:

val input2 = List("one", "two", "three", "four", "five")
for (entry <- input2.reduceLeft(_ max _)) println(input2.max)
Run Code Online (Sandbox Code Playgroud)

TAK*_*aki 10

你应该问自己:字符串列表的最大值是多少? List[String].maxString.max需要更多的澄清他们的任务.

  1. List.maxBy而不是List.reduceLeft

    input2.maxBy(_.length)
    
    Run Code Online (Sandbox Code Playgroud)
  2. 使用隐式类型转换

    implicit def string2ordering(s: String) = s.length
    input2.max
    
    Run Code Online (Sandbox Code Playgroud)