use of ~ sign in scala codes

170 views
Skip to first unread message

Ahmad

unread,
May 24, 2016, 11:06:05 AM5/24/16
to scala-user
I am sharing an example from book Programming in Scala by Martin Odersky et al.
def checksum(): Int = ~(sum & 0xFF) + 1

can somebody explain what this method is doing, especially "~" sign.

Thanks!

Timothy Kim

unread,
May 24, 2016, 2:14:46 PM5/24/16
to scala-user
~ is a method on Int defined here: http://www.scala-lang.org/api/2.11.8/index.html#scala.Int@unary_~:Int

According to the doc it returns the bitwise negation of this value.

If a method name starts with unary_ and followed by a symbol, you can invoke that method by prefixing an object with the symbol.

So

~(sum & 0xFF) + 1

Is same as

sum.&(0xFF).unary_~.+(1)

Naftoli Gugenheim

unread,
May 29, 2016, 4:52:21 PM5/29/16
to Timothy Kim, scala-user

... assuming that symbol is one of -, +, !, or ~ (i.e., the standard prefix operators in C-like languages).


--
You received this message because you are subscribed to the Google Groups "scala-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email to scala-user+...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Oliver Ruebenacker

unread,
May 31, 2016, 10:26:13 AM5/31/16
to Naftoli Gugenheim, Timothy Kim, scala-user

     Hello,

  I'm curious what a "C-like language" is? Some seem to define this as languages with blocks enclosed in curly braces. It would be an interesting observation if those languages that share curly braces also share the same set of unary operators.

     Best, Oliver
--
Oliver Ruebenacker
Senior Software Engineer, Diabetes Portal, Broad Institute

Timothy Kim

unread,
May 31, 2016, 3:07:17 PM5/31/16
to scala-user, nafto...@gmail.com, timot...@fastmail.fm
I'm not sure about "c-like" language, but scala spec declares these four symbols for prefix operator:

  PrefixExpr        ::=  [‘-’ | ‘+’ | ‘~’ | ‘!’] SimpleExpr

You can see the spec here: http://scala-lang.org/files/archive/spec/2.11/13-syntax-summary.html

Tim

som-snytt

unread,
Jun 1, 2016, 2:44:07 PM6/1/16
to scala-user, nafto...@gmail.com, timot...@fastmail.fm

My java-coder friend recently asked about tilde in my code. That surprised me.

c-like includes `++` etc. Let alone cast, `*` deref, `&`, `sizeof`.

Naftoli Gugenheim

unread,
Jun 1, 2016, 4:22:36 PM6/1/16
to Oliver Ruebenacker, Timothy Kim, scala-user
I'm sure there's no precise definition. But it you like, you can read my post as saying, "the standard prefix operators in C, as well as other languages that are similar to C in this regard." 😉
Reply all
Reply to author
Forward
0 new messages