Can't understand type errors in Scala
Here is the POC code:
object TypeTest extends Application {
val stuff = List(1,2,3,4,5)
def joined:String = stuff.reduceLeft(_ + ", " + _)
println(joined)
}
When compiled, it gives the following error:
tt.scala:4: error: type mismatch;
found : java.lang.String
required: Int
def joined:String = stuff.reduceLeft(_ + ", " + _)
^
tt.scala:4: error: type mismatch;
found : Int
required: String
def joined:String = stuff.reduceLeft(_ + ", " + _)
^
Writing a combined function like
reduceLeft(_.toString + ", " + _.toString)
doesn't help, still gives the same error. However, if I write it as
def joined:String = stuff.map(_.toString).reduceLeft(_ + ", " + _)
everything is good.
Can someone explain this weird combination of type errors? What's going on here? The second is especially odd since there is an implicit conversion for Int to String.
source to share
reduceLeft requires the function block (inside the parentheses) to return the same type as the collection. This is because the block is called recursively until all the values ββin the collection have been used.
stuff is List [Int], but (_ + "," + _) is a string, so a type error.
A similar method for decrementingLeft is foldLeft. The difference is that the collection type and the result type can be different. For example:
stuff.foldLeft("") { _ + ", " + _ } // => java.lang.String = , 1, 2, 3, 4
I assume your example is indicative, but if you really want a comma-separated string then it would be better:
stuff.mkString(", ") // => String = 1, 2, 3, 4
source to share
I started using Scala too. This is what I understand.
' stuff
' is a list of Int, so ' reduceLeft
' requires an Int parameter and returns Int (base on this ). But you put a string as a parameter (Error 1) and try to assign the result to a string (Error 2). This is why you got errors like this.
source to share