Why using the ~ operator in scala gives me a negative value

I am new to scala and tried to access the scala not statement. I found out that I can use the "-" operator for the logical NOT operation. But sometimes this operator gives me a negative answer such as (-1)

For instance:

val x = 1 val y =(~x) 

Here the y value gives me -1 instead of 0. But I need an answer in the form of 1 or 0. Can someone tell me what I'm missing here? Thank you for your help.

+5
source share
3 answers

Unlike many other languages, Scala does not support the use of numbers or other kinds of values ​​in contexts where the logical is expected. For example, none of the following lines compiles:

 if (1) "foo" else "bar" if ("1") "foo" else "bar" if (List(1)) "foo" else "bar" 

Some languages ​​have an idea of β€‹β€‹β€œveracity” that will be used here to determine if a condition is true, but Scala doesn't - if you want a boolean, you need to use Boolean .

This means that ordinary logical negation does not make sense for numbers, and ~ is something completely different - it gives you bitwise negation, which you do not want. Instead, it seems likely that you want something like this:

 val x = 1 val nonzeroX = x != 0 val y = !nonzeroX 

Ie, you explicitly convert your number to a boolean, and then work with it using standard boolean negation ( ! ).

+9
source

~ - bitwise negation, that is, it takes every bit of a given number and negates it, turning every 0-bit into 1-bit and every 1-bit into 0-bit. Since the first bit of a signed number denotes its sign (0 for positive numbers, 1 for negative), this leads to positive numbers and zero to turn negative (and vice versa).

If you want a simple logical negation, just use Booleans and ! .

PS: Please note that in the code you sent, the value of y will be -2 , not -1 , as you wrote in your message.

+3
source

If you just want to convert it from 0 to 1 or vice versa, you can use the ^ (XOR) operator.

 val x = 1 val y = 1^x 
+2
source

Source: https://habr.com/ru/post/1247431/


All Articles