Skip to content

Instantly share code, notes, and snippets.

@v6ak
Last active November 23, 2022 14:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save v6ak/34ea89a3da279ea42ea90661ea482c59 to your computer and use it in GitHub Desktop.
Save v6ak/34ea89a3da279ea42ea90661ea482c59 to your computer and use it in GitHub Desktop.
Dynamic typing vs. type inference
~/exp% /usr/lib/jvm/java-19/bin/javac Main.java
Main.java:13: error: cannot find symbol
System.out.println(x.length());
^
symbol: method length()
location: variable x of type Object
1 error
public class Main{
private static Object getValue() {
// We return String, but the type is just more generic Object
return "hello world";
}
public static void main(String...args) {
// javac sees that getValue() returns Object, so the type of x is also Object
var x = getValue();
// Although x contains a String, it is typed as Object, so we cannot call length() method.
// When we change the getValue()'s return type to String, it changes x's type to String and this file compiles.
// If we had a dynamic typing, we would be able to call length() anyway.
System.out.println(x.length());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment