What is the difference between unapply function and pattern matching and partial function

I have an extractor that extracts an object from a string.

case class ItemStructure(id: String, data: String)
object ItemStructure {
  def unapply(str: String): Option[ItemStructure] = {
    str.split('-').toList match {
      case List(id, data) => Some(ItemStructure(id, data))
      case _              => None
    }
  }
}

If I try to use this extractor in comparison with the sample, then everything will work as expected.

"" match {
  case ItemStructure(item) =>
}

It also works in a template corresponding to an anonymous function.

Option("").map {
  case ItemStructure(item) => 
}

Now, if I try to use this extractor in a partial function, the compiler will exit with the message: Cannot resolve overloaded unapply

val func: PartialFunction[Any, Unit] = {
  case ItemStructure(item) =>
}  

If I rename the companion object where the unapply function is located, everything works as expected.

Can someone explain why the extract does not work if it is in a companion object?

+4
source share
2 answers

ItemStructure.unapply: , case , . ItemStructure, String.

String, unapply, . unapply , Scala , .

unapply - , -, unapply - ( - ). , : ItemStructure.unapply unapply NewName.unapply, .

+4

Any , unapply. unappl y String.

:

val func: PartialFunction[String, Unit] = {
  case ItemStructure(item) =>
} 

unapply, Any.

+2

Source: https://habr.com/ru/post/1686636/


All Articles