3 ms·
This is the equivalent of casting in Java. Is Java's type system unsound?
by ng12 7y ago
This is the equivalent of casting in Java. Is Java's type system unsound?
- marcosdumay 7y agoThere is no casting in a sound type system. No language actually gets there, but there are some where developers mostly don't even remember there is a cast operation.
- lhorie 7y agoYou can't cast from a HashMap to an Animal class in Java, so in that sense Java is sounder. But you can still do `Animal a = null; a.walk();`, so in that sense, Java isn't sound.
- skn0tt 7y agoCorrect me if I'm mistaken: I think you can indeed cast from HashMap to Animal and it will happily compile: ```java import java.util.HashMap; class Main { class Animal { String sound = "roar"; } public static void main(String[] args) { HashMap<String, String> map = new HashMap<>(); Animal animal = (Animal) (Object) map; System.out.println(animal.sound); } } ``` At runtime, this will crash with the following Exception: `Exception in thread "main" java.lang.ClassCastException: class java.util.HashMap cannot be cast to class Main$Animal`, but it will satisfy the type system.
- lhorie 7y agoOh right, I totally forgot about casting to Object! So much for "sort of sound" haha
- DougBTX 7y agoYes, nice article on that here: https://hackernoon.com/java-is-unsound-28c84cb2b3f https://hackernoon.com/java-is-unsound-28c84cb2b3f