Scala Type Syntax

I noticed that if I want to create a universal function that can take a list of any type and return a boolean, I can use the following syntax to declare a function:

def someFunction[A](l:List[A]):Boolean 

However, I can also get an equivalent function declaration with this syntax:

 def someFunction(l:List[_]):Boolean 

The latter syntax makes sense to me; the underline indicates the template for a list of any type. However, the former are confusing; what is the semantic difference between the two types of syntax, if any? Note. I noticed that instead of the first syntax example, I could use [B] or [c] or even [%] instead of "[A]".

+5
source share
2 answers

A is a type parameter. Just like a value parameter, for example, your passed parameter l , it is a β€œname” or place holder for some type, which can be different at different times (that is, with different method calls).

In your example, A not used, yes, using _ makes more sense and is clearer, but if you have to return an element from the list, then the type of the returned method will be A (or whatever name you want to give this parameter). Using _ as the return type does not make sense.

+6
source

List[_] is an unbounded existential type and shorthand for List[X] forSome {type X <: Any} (which is similar to List<?> In Java).

In this case, I think that the types of functions (not in Scala syntax) are forall A. List[A] -> Boolean and (exists A. List[A]) -> Boolean mean the same thing, since in both cases you can only check the "form" of the list; probably there is equivalence between these types.

+1
source

All Articles