Hacker News new | ask | show | jobs
by skocznymroczny 3219 days ago
> In fact, I have the feeling this is a general trend across several relatively popular languages these days - provide as much as possible of the benefits of dynamic typing while keeping the benefits of static typing.

Some languages go the opposite way. Dart 1.0 has optional typing, but Dart 2.0 will be statically typed (with type inference though).

2 comments

> Dart 1.0 has optional typing, but Dart 2.0 will be statically typed (with type inference though).

Not quite; it's more that compile time typing is getting cleaned up. You can still omit types, which will then either be inferred or set to `dynamic`. The following is valid strong mode Dart:

  f(n) {
    if (n <= 1)
      return 1;
    else
      return n * f(n - 1);
  }

The following will no longer work:

  int x = "foo";
In short, you can still omit types. It's just that if you declare them, they are enforced [1]. Dart will also infer them if possible, i.e. the following is illegal:

  var x = 1;
  x = "foo";
Here, x is inferred to be `int`, which makes the assignment of a string illegal. However, the following works:

  var x = true ? 0 : [];
  x = "foo";
Here, the type of `x` cannot be inferred, so it becomes `dynamic`, and therefore the assignment of "foo" becomes valid.

You can turn this off with --no-implicit-dynamic; with this option, all types must either be declared or have to be inferable.

[1] Sometimes not at compile time, though: Dart allows implicit downcasts and covariant generics at compile time and will insert runtime checks to catch those situations.

> with type inference though

That is what I was trying to get at - with type inference, one can omit many of the type declarations (thus getting more flexibility and shorter code) without sacrificing type safety.

Whether or not it is a good idea to omit type declaration is a different question, but in cases like "T a = new T(...)", the type declaration on the variable is kind of redundant anyway.