LearningSlowly
LearningSlowly

Reputation: 9431

What does "!" mean in scala?

I am looking at a piece of code with the following:

graph.vertices.filter(!_._2._1)

I understand that _ are wildcard characters in scala but I do not know what the ! is supposed to do.

What does ! mean in scala?

Upvotes: 5

Views: 3754

Answers (2)

kc2001
kc2001

Reputation: 5247

As Robert said, ! is a method name. It can be tricky determining which ! method is being used. For example, in the line of code:

val exitValue = command.!(ProcessLogger(stdoutWriter.println, stderrWriter.println))

where command is a String (or Seq), command can be implicitly converted to a ProcessBuilder, so its ! method would apply. Your IDE may be able to help. IntelliJ IDEA Ultimate was able to tell me where ! was defined.

Upvotes: 0

Roberto Bonvallet
Roberto Bonvallet

Reputation: 33319

Scala doesn't have operators at the syntax level. All operations are methods.

For example, there is no add operator in the syntax, but numbers have a + method:

2.+(3)   // result is 5

When you write 2 + 3, that's actually syntax sugar for the expression above.

Any type can define a unary_! method, which is what !something gets desugared to. Booleans implement it, with the obvious meaning of logical negation ("not") that the exclamation mark has in other languages with C heritage.

In your question, the expression is an abbreviated form of the following call:

graph.vertices.filter { t => !(t._2._1) }

where t is a tuple-of-tuples, for which the first element of the second element has a type that implements unary_! and (as required by .filter) returns a Boolean. I would bet the money in my pocket that the element itself is a Boolean, in which case ! just means "not."

Upvotes: 13

Related Questions