The tilde operator in Scala

Firstly, some meta-advice. Any time you’re wondering how the compiler expands some syntactic sugar, infers a type, or applies an implicit conversion, use scala -Xprint:typer -e <expr> to show you what happened.

scala -Xprint:typer -e "val a = 2; ~a"

...
private[this] val a: Int = 2;
private <stable> <accessor> def a: Int = $anon.this.a;
$anon.this.a.unary_~

Okay, a prefix ~ is expanded to a regular method invocation of unary_~.

From the language specification:

6.12.1 Prefix Operations

A prefix operation op e consists of a prefix operator op, which must be one of the identifiers +, -, ! or ~.
The expression op e is equivalent to the postfix method application
e.unary_op.

Prefix operators are different from normal function applications in
that their operand expression need not be atomic. For instance, the
input sequence -sin(x) is read as -(sin(x)), whereas the function
application negate sin(x) would be parsed as the application of the
infix operator sin to the operands negate and (x).

That means that the prefix operators aren’t restricted to built in types, they can be used on your own types (although it’s not a good idea to go crazy with this power!)

scala> object foo { def unary_~ = "!!!" }
defined module foo

scala> ~foo
res0: java.lang.String = !!!

So, what of your question? You can checkout the index of the ScalaDoc for the standard library for methods starting with u. The nightly ScalaDoc has some recently added documentation for this method.

the bitwise negation of this value
Example:
~5 == -6
// in binary: ~00000101 ==
//             11111010

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)