Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does List in Scala is not homogeneous collection?

I have this following function which set the head of list with new value

  def setHead[A](ls: List[A], ele: A):List[A] = {
    ls match {
    case Nil => ls
    case x :: xs => ele :: xs
    }
  }

and output of this after calling it with

println(setHead(List(-1,-2,-3,4,5,6), (x :Int)  =>  x < 0))

is

List(<function1>, -2, -3, 4, 5, 6)

But the function takes a type 'A' argument and I am passing a list with type 'Int' and a function then how does it compile and run because type 'A' cant be Int and at the same time.

like image 634
Saurabh kukade Avatar asked Dec 06 '25 13:12

Saurabh kukade


3 Answers

Both Int and Int => Boolean inherit from Any, which is the root of the Scala class hierarchy:

  • Int inherits from AnyVal, which inherits from Any.
  • Int => Boolean inherits from AnyRef, which inherits from Any.

And we can check the type of an expression in the Scala REPL in a couple of ways:

scala>  def setHead[A](ls: List[A], ele: A):List[A] = ls match {
     |    case Nil => ls
     |    case x :: xs => ele :: xs
     |  }
setHead: [A](ls: List[A], ele: A)List[A]

scala> setHead(List(-1,-2,-3,4,5,6), (x :Int)  =>  x < 0)
res0: List[Any] = List($$Lambda$1256/1374785073@3290b1a6, -2, -3, 4, 5, 6)

scala> :type setHead(List(-1,-2,-3,4,5,6), (x :Int)  =>  x < 0)
List[Any]
like image 148
dkim Avatar answered Dec 08 '25 12:12

dkim


By calling setHead() the way you did, the compiler will conclude A as Any which is the lowest common ancestor of Int and Int => Boolean:

setHead(List(-1, -2, -3, 4, 5, 6), (x :Int) => x < 0)
// res1: List[Any] = List(<function1>, -2, -3, 4, 5, 6)

The compiler would've complained, had you made A explicit:

setHead[Int](List(-1, -2, -3, 4, 5, 6), (x :Int) => x < 0)
// <console>:16: error: type mismatch;
// found   : Int => Boolean
// required: Int
like image 26
Leo C Avatar answered Dec 08 '25 12:12

Leo C


Both Int and Int => Boolean inherit from Any, which is the root of the Scala class hierarchy:

  • Int inherits from AnyVal, which inherits from Any.
  • Int => Boolean inherits from AnyRef, which inherits from Any.

And we can check the type of an expression in the Scala REPL in a couple of ways:

scala>  def setHead[A](ls: List[A], ele: A):List[A] = ls match {
     |    case Nil => ls
     |    case x :: xs => ele :: xs
     |  }
setHead: [A](ls: List[A], ele: A)List[A]

scala> setHead(List(-1,-2,-3,4,5,6), (x :Int)  =>  x < 0)
res0: List[Any] = List($$Lambda$1256/1374785073@3290b1a6, -2, -3, 4, 5, 6)

scala> :type setHead(List(-1,-2,-3,4,5,6), (x :Int)  =>  x < 0)
List[Any]
like image 42
dkim Avatar answered Dec 08 '25 12:12

dkim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!