Grant Park
Grant Park

Reputation: 1044

Scala Type Syntax

I've observed that, if I want to make a generic function that can accept a list of any type and return a boolean, I can use the following syntax for a function declaration:

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

However, I can achieve an equivalent function declaration with this syntax as well:

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

The latter syntax makes sense to me; the underscore indicates a wildcard for a List of any type. However the former is confusing; what's the semantic difference between the two types of syntax, if there is one at all? Note: I noticed I could use [B] or [c] or even [%] in place of the "[A]" in the first syntax example.

Upvotes: 5

Views: 153

Answers (2)

phipsgabler
phipsgabler

Reputation: 20980

List[_] is an unconstrained existential type and shorthand for List[X] forSome {type X <: Any} (which is like List<?> in Java).

In this case, I think the function types (not in Scala syntax) forall A. List[A] -> Boolean and (exists A. List[A]) -> Boolean denote the same things, since in both cases you can only inspect the "shape" of the list; probably there's an equivalence between those types.

Upvotes: 1

jwvh
jwvh

Reputation: 51271

The A is a "type parameter". Just like a value parameter, such as your l passed parameter, it is the "name", or place holder, for a some type which might be different at different times (i.e. with different invocations of the method).

In your example the A is unused so, yeah, using _ makes more sense and is clearer, but if you were to return an element from the list then the method return type would be A (or whatever name you want to give that parameter). Using _ as a return type wouldn't make any sense.

Upvotes: 6

Related Questions