What does the ~ do in this bit of Scala?
For example:
scala> val apple = 1 apple: Int = 1 scala> ~apple res0: Int = -2
What did that worm do to my apple?
In Scala a ~ b. means a.~(b) So it calls the method ~ on a and gives b as an argument.
On Scala Collections there is usually :+ and +: . Both add an element to the collection. :+ appends +: prepends. A good reminder is, : is where the Collection goes. There is as well colA ++: colB to concat collections, where the : side collection determines the resulting type.
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 expressionop e
is equivalent to the postfix method applicatione.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 negatesin(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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With