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.
The ::() operator in Scala is utilized to add an element to the beginning of the List.
Whether an integer is positive or negative (the sign of the integer) is stored in a dedicated bit, the sign bit. The bitwise NOT affects this bit, too, so any positive number becomes a negative number and vice versa.
It has no special meaning whatsoever. It is also not a well-known method name in Scala. It seems to come from some library; you need to look at the documentation of whatever library you are using to figure out what it does.
It means an abstract type member is defined (inside some context, e.g. a trait or class), so that concrete implementations of that context must define that type.
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 (!
).
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