0

I have just started learning scala and I am pretty confused with Generics:

Question 1:

def getRemainingItem[X](list : List[X], fun : (X) => Boolean) : List[X] = {
    list.filterNot(fun)
}

What is X here looks like E of Java(This code works fine)

Question 2:

def getRemainingItem(list : List[Any], fun : (Any) => Boolean) : List[Any] = {
    list.filterNot(fun)
}

Why is Any not working. I am thinking Any can accept any type (this isn't compiling)

Question 3:

def getRemainingItem(list : List[_], fun : (_) => Boolean) : List[_] = {
    list.filterNot(fun)
}

Again this is not working and what is the difference between "_" and "Any"

Chris Martin
  • 30,334
  • 10
  • 78
  • 137
secret129
  • 191
  • 1
  • 10

1 Answers1

0

Answer 1: X is a generic type parameter. So method getRemainingItem is a generic method which will be called with a concrete type argument (a type instantiation such as X = Int).

Answer 2: that code snippet does compile (tested with Scala 2.11)

Answer 3: a type T[_] is a shortcut for T[X] forSome { type X } (which is an existential type). This is similar to Java wildcards (https://docs.oracle.com/javase/tutorial/extra/generics/wildcards.html). Of course, saying "some unknown type T" is different from saying "Any" (which is a concrete type -- the top type).

For more information: - What is an existential type?

Community
  • 1
  • 1
metaphori
  • 2,681
  • 1
  • 21
  • 32