Home > OS >  Scala: Adding native types to type parameter list throws an error
Scala: Adding native types to type parameter list throws an error

Time:03-10

When defining type parameter lists in Scala functions, it introduces type variables that can be referenced in signature of the function, e.g.

def test[A,B,C] (a: A, f: (A,B) => C): B => C 

My question may be trivial, but I can not seem to figure out why

def sum[Int](l: List[Int]): Int = { 
    l.foldLeft(0)((a, b) => a  b ) 
} 

Throws

None of the overloaded alternatives of method   in class Int with types
 (x: Double): Double
 (x: Float): Float
 (x: Long): Long
 (x: Int): Int
 (x: Char): Int
 (x: Short): Int
 (x: Byte): Int
 (x: String): String
match arguments ((b : Int))mdoc

Whereas simply removing the type parameter [Int] compiles completely fine.

def sum(l:List[Int]): Int = { 
    l.foldLeft(0)((x, y) => x   y)
}

CodePudding user response:

In sum[Int](l: List[Int]): Int method definition you are actually declaring a generic type parameter called Int which just matches the name of predefined type but is not related to it so compiler fails to find a valid method.

  • Related