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?
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.
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.
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.
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.
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.
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