简体   繁体   中英

Why is the declaration of type important in a statically typed language?

I'm trying to understand the benefit of a programming language being statically typed, and through that, I'm wondering why we need to include type in declaration? Does it serve any purpose rather than to make type explicit? If this is the case, I don't see the point. I understand that static typing allows for type checking at compile-time, but if we leave out the explicit type declaration, can't Java still infer type during compile-time?

For example, let's say we have in Java:

myClass test = new myClass();

Isn't the type declaration unnecessary here? If I'm not mistaken, this is static binding, and Java should know test is of type myClass without explicit declaration of type even at compile-time.

Response to possible duplicate: this is not a question regarding static vs. dynamic type, but rather about type inference in statically typed languages, as explained in the accepted answer.

There are statically typed languages that allow you to omit the type declaration. This is called type inference . The downsides are that it's tougher to design (for the language designers), tougher to implement (for the compiler writers), and can be tougher to understand when something goes wrong (for programmers). The problem with the last one of those is that if many (or all) of your types are inferred, the compiler can't really tell you much more than "the types aren't all consistent" — often via a cryptic message.

In a trivial case like the one you cite, yes, it's easy. But as you get farther from the trivial case, the system quickly grows in complexity.

Java does actually do a bit of type inference, in very limited forms. For instance, in this snippet:

List<String> emptyStrings = Collections.emptyList();

... the compiler has inferred that the method call emptyList returns a List<String> , and not just a List<T> where the type T is unspecified. The non-inferred version of that line (which is also valid Java) is:

List<String> emptyStrings = Collections.<String> emptyList();

It is necessary. You can have inheritance, where types are necessary.

For example:

Building build1 = new House();
Building build2 = new SkyScraper();

It is the same in polymorphism.

You can then collect all Building s to array for example. If there will be one House and one SkyScraper you can't do this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM