Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The tilde operator in Scala

Tags:

scala

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?

like image 878
Jack Avatar asked Feb 25 '12 08:02

Jack


People also ask

What is tilde in Scala?

In Scala a ~ b. means a.~(b) So it calls the method ~ on a and gives b as an argument.

What does :+ mean in Scala?

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.


1 Answers

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 
like image 156
retronym Avatar answered Sep 17 '22 18:09

retronym