Last active
November 23, 2022 14:49
-
-
Save v6ak/34ea89a3da279ea42ea90661ea482c59 to your computer and use it in GitHub Desktop.
Dynamic typing vs. type inference
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
~/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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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