A simple question about Scala generics

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

Consider, for example, two functions below:

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

What is the difference between these ads above?

+4
source share
2 answers

The first is the existential type, and the second is the ordinary type. Actually the first syntax means this:

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

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

Intuitively, X[_] means that a parameter of type x does not matter, while X[Any] says that it should be Any .

+9
source

Slight difference

 scala> class X[T] defined class X scala> def type_of[T](x: X[T])(implicit m: Manifest[T]) = m.toString type_of: [T](x: X[T])(implicit m: Manifest[T])java.lang.String scala> val x1: X[Any] = new X x1: X[Any] = X@1a40cfc scala> val x2: X[_] = new X x2: X[_] = X@29d838 scala> type_of(x1) res10: java.lang.String = Any scala> type_of(x2) res11: java.lang.String = _ <: Any 

I cannot name a situation when you can use Any, but you cannot use _ and vice versa.

-1
source

Source: https://habr.com/ru/post/1344310/


All Articles