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?

Daniel Werner
  • 1,350
  • 16
  • 26
marstran
  • 26,413
  • 5
  • 61
  • 67

1 Answers1

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.

tryx
  • 975
  • 7
  • 17
  • Does the second example allow you to pass arguments? – ReyCharles Jul 17 '15 at 08:46
  • 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. – tryx Jul 17 '15 at 08:52
  • 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? – marstran Jul 17 '15 at 09:19
  • 1
    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. – tryx Jul 17 '15 at 15:13