Method overloading unapply in class classes: scala

Consider the following code snippet:

case class User(id: Int, name: String)
object User{
  def unapply(str: String) = Some(User(0, str))
}

Scala complains "error: cannot overload unapply; class case User (id: Int, str: String)" Is it not possible to repack the excess?

update: unapply with a large tuple size.

case class User(id: Int, str: String)
object User{
  def unapply(s: String) = Some((User(0, s), s, 1234))
}

the compiler still complains "cannot allow unapply overloading"

+5
source share
2 answers

Your unapply method cannot be used when matching patterns

He works with

def unapply(arg: <type to match>) : Option[(<matched fields types>)]

(there is no tuple if there is only one field, instead of boolean instead of the option if there is no field).

The standard non-use of the user will be (Scala Language Specification p. 67)

def unapply(u: User) = 
  if (u eq null) None 
  else Some((u.id, u.name))

This is what you want to match the user with a null identifier, as in

user match {case User(name) => ....}

which would be

def unapply(u: User): Option[String] = 
  if(u eq null || u.id != 0) None 
  else Some(u.name)

, ( )

def unapply(s: String): Option[User] = Some(User(0, s))

"john" match case User(u) => ... // u is User(0, john)

, . , - ( ), . , , , .

, , . - , . , , .

+8

, unapply (), , , , case. , signiture .

+1

All Articles