30

Seen tilde in a few code examples in Dart. I've seen it used in C++ as a destructor where it can be called to delete the instance of a object Has it the same function in Dart? Is there an equivalent symbol in Java?

flutter
  • 6,188
  • 9
  • 45
  • 78

2 Answers2

35

Dart doesn't support destructors

https://www.dartlang.org/guides/language/language-tour#operators

~ is currently only used for

~/ Divide, returning an integer result

and ~/= integer division and assignment.

There is not really an equivalent in Java.
In Java the result is an integer if the result is assigned to an integer variable (not sure though, not a Java dev)

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • 4
    In Java, the result is an integer if both numbers are integers. It performs integer division and truncates the decimal portion (everything after the dot). `int a = 2; int b = 3;` and `a/b` => `0` if you don't want to lose precision cast one of the numbers to float or double: `(double)a/b` => `0.66....` – Kirill Karmazin Aug 02 '19 at 12:15
  • ~/ also truncates the decimal portion. – John Pankowicz May 26 '20 at 14:03
  • 2
    @JohnPankowicz that's what "returning an integer result" means. – Günter Zöchbauer May 26 '20 at 14:21
  • 1
    @GünterZöchbauer - No it doesn't. There are also operators in other languages that perform rounding to return an integer result. – John Pankowicz May 26 '20 at 14:27
24

The ~ operator is an overloadable operator on Dart objects, so it can mean anything you want it to. In the platform libraries, the only use is int.operator~ which does bitwise negation (like the similar integer operator in C, Java and JavaScript).

As Günther Zöchbauer mentions, the ~ also occurs in the overloadable ~/ operator which the platform libraries uses for integer division as num.operator~/. There is no relation between the ~ or ~/ operators by default.

So, it does not mean "destruction". Dart does not allow explicit destruction, or any destruction at all - the language specification doesn't say when an object dies. (Implementations garbage collect objects that the user code cannot see any more, to preserve memory).

lrn
  • 64,680
  • 7
  • 105
  • 121