简体   繁体   中英

Difference between any and parametric polymorphism scala?

I know that parametric polymorphism is what actually works, but I'm curious why using Any in it's place does not. For example how is the first function

def len[T] (l:List[T]):Int = 


 l match {
    case Nil    => 0
    case _ :: t => 1 + len(t)
  }

different from this one?

def len (l:List[Any]):Int = 
  l match {
    case Nil    => 0
    case _ :: t => 1 + len(t)
  }

What do you mean it doesn't work? This seems fine:

len(List('a,'b,'c))
// res0: Int = 3

Your in your example, there really isn't a difference, since you're not actually using the contents of the list for anything, but imagine a slightly different function:

def second[T](l: List[T]): Option[T] = 
  l match {
    case Nil    => None
    case _ :: Nil    => None
    case _ :: x :: _ => Some(x)
  }

println(second(List(1,2,3)).map(_ + 5))                           // Some(7)
println(second(List(List('a,'b,'c), List('d,'e))).map(_.head))    // Some('d)

If you tried this with Any , you wouldn't be able to get anything except Option[Any] in return, so the compiler wouldn't let you do anything useful with the result (like add it to an Int or call .head , as in the examples, respectively).

In this case there really isn't a difference, because you aren't relying on the contained type at all, just the structure of List itself. It doesn't matter what T is, the length will be the same either way.

The type parameter would be important if you wanted to return another List[T] . For example:

def takeEveryOther[T](l: List[T]): List[T] =
    l.zipWithIndex.collect { case (a, i) if(i % 2 == 0) => a }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM