我正在阅读 OCaml 和 wiki,它说:
*its static type system renders runtime type mismatches impossible*
我明白为什么,但后来我想,为什么这在 OCaml(和 FP)中如此特别?你如何导致运行时类型不匹配,比如 Java?例如
boolean a = true;
int b = a + 1;
会在编译时返回一个错误。
编辑 1:
haskell
func :: Int -> Bool
func i = if i > 0 then True else False
Java
boolean func (int i) {
if (i > 0) return true; else return false;
}
func
调用时,两者不都保证参数类型吗?
最佳答案
在 Java 中,您可以像这样导致运行时类型不匹配:
Object i = Integer.valueOf(6);
String s = (String) i;
System.out.println(s);
这将编译,因为 i
(Object
) 的编译时类型被允许转换为 String
,但是在运行时,i
的实际值(6
,作为 Integer
)将与 String
不兼容。
鉴于此,将抛出一个 ClassCastException
。
关于java - Java 中是否可能存在运行时类型不匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29348673/