After seeing the method signature of map in scala as
def map[A, B](l: List[A])(f: A => B): List[B] = ???
my layman undersanting of [A, B] in above is that they signal the method that we'll be exclusively working with generic Type A and B in the defined method.
Now I go on to implement a method to add values from two lists consquetively (basically zipWith) using similar coding pattern.
def addCorresponding[Int](l1: List[Int],
l2: List[Int]): List[Int] =
(l1, l2) match {
case (_, Nil) => Nil
case (Nil, _) => Nil
case (x::xs, y::ys) => {
List((x + y)) ++ addCorresponding(xs, ys)
}
}
but get this error while adding the elements in the last match: type mismatch found: Int Required: String
Removeing the [Int] from the mehtod sigature fixes this error.
I'm sure there are holes in my understanding of generic Types and when to add them to the method signature. I'd appreciate if someone can walk me through this and explain why the addCorresponding method with [Int] errors out but works fine without it?
def plusFive(x: Int): Int = x + 5, what isx? Anything, whatever is passed to the function. It is not1, nor0nor even5or3, it is just a parameter. So in the first exampleAandBare parameters for types, meaning they are not any proper type right now, they will be filled by the compiler when called. In your second example you want both lists to be of type Int since you want to sum the elements, that is something you can only do with Ints, so not need to add a type parameter. - Luis Miguel Mejía Suárez[Int]you are creating a type parameter namedIntwhich shadows the type Int, that is why it doesn't work when you add that. - Luis Miguel Mejía Suárezzip? It does exactly what you are trying to do. scastie.scala-lang.org/yYCapPvmSgWWE467QRh4ZQ - Tomer Shetah