0

I have a class with the following method:

def message[A <: AnyRef](a: A) = a match {
  case str: String => messages ++ str
  case _: AnyRef => serializer.write(_) //compile error
}

I thought _ may be used in any situation we don't want to use some specific character. But

def message[A <: AnyRef](a: A) = a match {
  case str: String => messages ++ str
  case a: AnyRef => serializer.write(a)
}

works fine.

What's a problem with _? What is the limit of its usage as method parameters?

user3663882
  • 6,957
  • 10
  • 51
  • 92
  • 1
    https://stackoverflow.com/questions/8000903/what-are-all-the-uses-of-an-underscore-in-scala – dveim Sep 02 '16 at 11:04

2 Answers2

2

case _: AnyRef => serializer.write(_) these wildcards are not related. Your first _ means that you don't care about the name you just give it a type. The second _ means that you don't care what will be provided to write at the moment and you will provide it later. The _ in your code are not related, as you might have thought.

sebszyller
  • 853
  • 4
  • 10
1

Error happens in serializer.write(_), because compiler does not have any possible values for this _. For example, if you'd write List(1, 2, 3) map (_ + 2), that could be expanded to List(1, 2, 3) map (x => x + 2), and there x might be hidden with _.

dveim
  • 3,381
  • 2
  • 21
  • 31