2

What is wrong with this code?

object Numbers extends App {

  def decode(number: Int) : String = number match {
    case _ if _ % 15==0 => "fizzbuzz"
    case _ if _ % 3==0 => "fizz"
    case _ if _ % 5==0 => "buzz"
    case _ => _.toString
  }

  val test = List(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15)
  test.map(decode).foreach(println)
}

I get the following error:

error: missing parameter type for expanded function
The argument types of an anonymous function must be fully known. (SLS 8.5)
Expected type was: String
case _ if _%15==0 => "fizzbuzz"

Why the compiler does not know the parameter type? Thanks

1 Answer 1

6

(_ % 15 == 0) is expanded to a function (x: ?) => x % 15 == 0. Same for the other if checks.
The compiler can't infer it because it has no information about the parameter, it's a fresh name with no relation to the previous underscore in case _. So you can't use the underscore there to refer to the matched name, you have to actually assign it a name, as in case x if x % 15 == 0

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.