Search code examples
scalafunctional-programmingfold

In Scala, is Int a super-type of List[Int] and how so?


Taking a look at this example:

val list = List(1, 2, 3, 4, 5) 
val sum = list.fold(0)((x, y) => x + y) 
assert(sum == 15)

And the method signature of fold:

fold[A1 >: A](z: A1)(op: (A1, A1) => A1): A1

Am assuming A is type List[Int] and A1 is type Int. According to the official docs for fold, A1 is a type parameter for the binary operator, a supertype of A. If my assumption above is correct, then Int is a super-type of List[Int] in the above sum example. Some blog posts like this one actually state this explicitly. Clearly, List[Int] does not extend Int. So my question: Is Int a super-type of List[Int] and how so?


Solution

  • The A is the type variable bound in the List[+A] type constructor itself: it's towards the top of the documentation page that you linked, in

    sealed abstract class List[+A]
    

    Your list-variable is of type List[Int], so A is Int. The A1 in fold must be a supertype of Int, in this case, both A and A1 >: A are therefore just Int (not List[Int])


    Regarding the link to the blog: it indeed includes the sentence

    Int is a supertype of List[Int]

    This is plain wrong. You can easily check this as follows:

    scala> implicitly[List[Int] <:< Int]
                     ^
           error: Cannot prove that List[Int] <:< Int.