Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unbound Wildcard Type

I was playing around in the Scala REPL when I got error: unbound wildcard type. I tried to declare this (useless) function:

def ignoreParam(n: _) = println("Ignored")

Why am I getting this error?

Is it possible to declare this function without introducing a named type variable? If so, how?

like image 962
marstran Avatar asked Jul 17 '15 08:07

marstran


People also ask

What is unbounded wildcard?

The unbounded wildcard type is specified using the wildcard character (?), for example, List<?>. This is called a list of unknown type. There are two scenarios where an unbounded wildcard is a useful approach: If you are writing a method that can be implemented using functionality provided in the Object class.

What is wildcard types in Java?

Wildcards in Java are basically the question marks which we use in generic programming, it basically represents the unknown type. We use Java Wildcard widely in situations such as in a type of parameter, local variable, or field and also as a return type.

What is the use of wildcard in generics?

The question mark (?) is known as the wildcard in generic programming. It represents an unknown type. The wildcard can be used in a variety of situations such as the type of a parameter, field, or local variable; sometimes as a return type.

Do not use wildcard types as return types?

It is highly recommended not to use wildcard types as return types. Because the type inference rules are fairly complex it is unlikely the user of that API will know how to use it correctly.


1 Answers

Scala doesn't infer types in arguments, types flow from declaration to use-site, so no, you can't write that. You could write it as def ignoreParam(n: Any) = println("Ignored") or def ignoreParam() = println("Ignored").

As it stands, your type signature doesn't really make sense. You could be expecting Scala to infer that n: Any but since Scala doesn't infer argument types, no winner. In Haskell, you could legally write ignoreParam a = "Ignored" because of its stronger type inference engine.

To get the closest approximation of what you want, you would write it as def ignoreParams[B](x: B) = println("Ignored") I suppose.

like image 66
tryx Avatar answered Sep 27 '22 22:09

tryx