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.
Scala is a statically typed programming language. This means the compiler determines the type of a variable at compile time. Type declaration is a Scala feature that enables us to declare our own types.
Language. Methods in Scala can be parameterized by type as well as by value. The syntax is similar to that of generic classes. Type parameters are enclosed in square brackets, while value parameters are enclosed in parentheses.
=> is syntactic sugar for creating instances of functions. Recall that every function in scala is an instance of a class. For example, the type Int => String , is equivalent to the type Function1[Int,String] i.e. a function that takes an argument of type Int and returns a String .
A higher-kinded type can have one or more other types as parameters. In Scala, you can do this using the type keyword.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With