Reputation: 967
I am new to scala and was trying to access the scala not operator. I got to know that I could use the '-' operator for logical NOT operation. But sometimes this operator gives me a negative answer such as (-1)
For example :
val x = 1
val y =(~x)
Here the value y gives me a -1 instead of a 0. But I need the answer in the form of a 1 or a 0. Can somebody tell me what am I missing here ? Thank you for your help in advance.
Upvotes: 5
Views: 1435
Reputation: 139058
Unlike many other languages, Scala doesn't support using numbers or other kinds of values in contexts where a boolean is expected. For example, none of the following lines compile:
if (1) "foo" else "bar"
if ("1") "foo" else "bar"
if (List(1)) "foo" else "bar"
Some languages have an idea of "truthiness" that'd be used here to determine whether the condition holds, but Scala doesn't—if you want a boolean, you need to use a Boolean
.
This means that ordinary logical negation doesn't make sense for numbers, and ~
is something completely different—it gives you bitwise negation, which isn't what you want. Instead it seems likely you want something like this:
val x = 1
val nonzeroX = x != 0
val y = !nonzeroX
I.e., you explicitly transform your number into a boolean value and then work with that using standard logical negation (!
).
Upvotes: 9
Reputation: 4256
If you just want to convert it from 0
to 1
or vice-versa you can use ^
(XOR) operator.
val x = 1
val y = 1^x
Upvotes: 2
Reputation: 370465
~
is bitwise-negation, that is it takes each bit of the given number and negates it, turning each 0-bit into a 1-bit and each 1-bit into a 0-bit. Since the first bit of a signed number denotes its sign (0 for positive numbers, 1 for negative), this causes positive numbers and zero to turn negative (and vice versa).
If you want simple logical negation, just use Booleans and !
.
PS: Note that in the code you posted, the value of y
will be -2
, not -1
as you wrote in your post.
Upvotes: 4