Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does using the '~' operator in scala give me a negative value

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.

like image 792
Goldengirl Avatar asked Apr 19 '16 13:04

Goldengirl


People also ask

What is :: operator in Scala?

The ::() operator in Scala is utilized to add an element to the beginning of the List.

Why is Bitwise not negative?

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.

What does =!= Mean in Scala?

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.

What does <: mean in Scala?

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.


1 Answers

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 (!).

like image 95
Travis Brown Avatar answered Sep 20 '22 18:09

Travis Brown