4

I have a method:

  def replaceSpecialSymbols(str: String): String = str.collect {
    case '/'     => '-'
    case _ => _
  }.toString

Whe I try to build this code, I receive the error message: "error: unbound placeholder parameter case _ => _"

I know that I can use replaceAll. But I want to know what is going on in this case in Scala compiler.

Thank you.

Nikolay
  • 53
  • 1
  • 6
  • Look at this http://stackoverflow.com/questions/1025181/hidden-features-of-scala/1083523#1083523 for clarity on the rules for placeholders in relation to anonymous functions. – hellraiser Oct 30 '14 at 12:21

1 Answers1

5

Use case x => x — problem solved. Also, you can just use map instead of collect because it's an exhaustive match.

Or if you only need the first case, just remove that case _ => _ altogether and keep using collect.

Erik Kaplun
  • 37,128
  • 15
  • 99
  • 111
  • Erik thank you. I know how to solve this problem. I want to know why it does not work. What is wrong, why scala return this exception "unbound placeholder parameter". – Nikolay Oct 30 '14 at 12:46
  • 2
    @Nikolay, it happens because `_` is special in Scala. In particular, in pattern matches `_` means that corresponding pattern should be ignored - it does not bind the value to `_` identifier, so it does not make sense to use it as a standalone identifier. – Vladimir Matveev Oct 30 '14 at 12:50
  • Vladimir thank you. This is a good explanation. Can you post it like standalone answer? – Nikolay Oct 30 '14 at 13:00
  • 1
    Sorry, I missed the last part of your question — Vladimir's right: the first `_` is a pattern match; the second one is completely unrelated to the first one and Scala sees no reason for it to be there, so it says it's "unbound". – Erik Kaplun Oct 30 '14 at 13:34
  • P.S. in other words, smth like `3 match { case _ => (_: Int) * 2 }` will compile because the `_` in the case body is meaningful because it's bound to its surrounding lambda expression; just a lone `_` means nothing. – Erik Kaplun Oct 30 '14 at 13:41
  • Erik in your case I receive a function: scala> 3 match { case _ => (_: Int) * 2 } res13: Int => Int = – Nikolay Oct 30 '14 at 14:37