Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple question about Scala generics

Tags:

generics

scala

What is the difference between X[Any] and X[_] ?

Let's consider, for example, two functions below:

def foo(x:X[_]){}
def foo(x:X[Any]){}

What is exactly the difference between these declarations above?

like image 632
Michael Avatar asked Feb 24 '23 18:02

Michael


1 Answers

The first is an existential type, and the second is a normal type. The first syntax actually means this:

def foo(x:X[t] forSome { type t }){}

What this means is that x is of type X[t], where t can be any unspecified type t.

Intuitively, X[_] means the type parameter of X is irrelevant, whereas X[Any] says it must be Any.

like image 88
Daniel C. Sobral Avatar answered Mar 08 '23 04:03

Daniel C. Sobral