Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Longest word in List

Tags:

list

scala

I have a List with Strings and I want to print the longest String out of it

I have tried the reduceLeft option but whenever I am applying it its returning this error:

type mismatch; found:String required:Ordering[?]

Here is the code throwing the exception in the second line:

val input2 = List("one", "two", "three", "four", "five")
for (entry <- input2.reduceLeft(_ max _)) println(input2.max)
like image 218
bajro Avatar asked Dec 08 '22 03:12

bajro


1 Answers

you should ask yourself: What is the max for a list of Strings? List[String].max and String.max need more clarification for their task.

  1. use List.maxBy instead of List.reduceLeft

    input2.maxBy(_.length)
    
  2. use implicit type conversion

    implicit def string2ordering(s: String) = s.length
    input2.max
    
like image 199
TAKASAKI Hiroaki Avatar answered Dec 27 '22 11:12

TAKASAKI Hiroaki