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.
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]
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
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With