简体   繁体   中英

What does `val (_, x) = …` mean in Scala?

I'm trying to understand this scala code (modified from here ):

val ConnectionDefinition(_, eventConnection) =
  Connection.definition[EventRepo, Connection, Event]("Event", EventType)

This is inside an object . It seems like it's using the return value of the function Connection.definition[EventRepo, Connection, Event]("Event", EventType) to instantiate a case class, unpacking the return values(?), but:

  1. Why is it just val ConnectionDefinition(_, eventConnection) ? Is this some sort of anonymous value or something since there's no identifier (eg val myVal = ... .
  2. Why even bother to give any of the arguments to ConnectionDefinition names (ie eventConnection )?

The val that is being defined is eventConnection , which is the second parameter in the deconstruction ( unapply ) of the ConnectionDefinition instance returned by the call to Connection.definition . Now eventConnection will be available to the rest of the code (the rest of the ConnectionDefinition instance returned will not be, but presumeably isn't required).

What you see is a destructuring assignment with the first value ignored.

ConnectionDefinition is a case class with two values. A case class automatically implements an extractor (the unapply method) which is called when you pattern match.

Here are some things you can do with this language feature:

case class ConnectionDefinition(edgeType: ObjectType, connectionType: ObjectType)
object Connection {
  def definition(): ConnectionDefinition = ???
}

// basic assignment:
val conn = Connection.definition()
val conn: ConnectionDefinition = Connection.definition()

// extract the two values from the case class:
val ConnectionDefinition(edgeType, connType) = Connection.definition()
val ConnectionDefinition(edgeType: ObjectType, connType: ObjectType) = Connection.definition()

// extract only one value and ignore the other:
val ConnectionDefinition(edgeType, _) = Connection.definition()
val ConnectionDefinition(_, connType) = Connection.definition()

// extract both values AND still keep a reference to the whole ConnectionDefinition
val conn @ ConnectionDefinition(edgeType, connType) = Connection.definition()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM