Unbound Wildcard Type
Asked Answered
S

1

6

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?

Sharecropper answered 17/7, 2015 at 8:36 Comment(0)
G
14

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.

Girandole answered 17/7, 2015 at 8:45 Comment(4)
Does the second example allow you to pass arguments?Idaline
No, that would be a 0-arity function. You could also write it in the 3rd form I just added in an edit which might be more like what you want.Girandole
Thanks, but isn't def ignoreParam(x: _) = println("Ignored") the same as def ignoreParam[B](x: B) = println("Ignored") except for the declaration of type parameter B? Why does it matter if I declare B or not?Sharecropper
Without getting into too much language lawerying and referring to the spe, when you write ignoreParams[B] you are telling the compiler that there is SOME type B that will fulfill that contract. I can see how you may want to put the underscore there and it is totally intuitive to given how _is used in the rest of the language to indicate things that we don't care about, but the construct that you want just isn't in Scala. I imagine that it's not something that is useful enough to be in the spec because of how rare it would be, or it violates type inferences in some subtle way.Girandole

© 2022 - 2024 — McMap. All rights reserved.