Bul*_*ula 0 inheritance scala hierarchy subtype
我正在学习Martin Odersky的课程中的scala课程.他给出了一些关于返回类型的精彩例子,有一件事困惑我:
if(true) 1 else false // return AnyVal as this is the closest subtype of both primitive types
我假设以下内容:
if(true) Tweet.comment("hello") else String("Hello") // I assume that this code will return AnyRef
但scala什么时候会返回Any?它会永远归还吗?
@dfeuer的回答是正确的,我只是想补充一些信息.
AnyVal是用于原始的类型,即基类型Int,Boolean,Byte等.在Java中,这些是"关键字"类型int,boolean,byte.
AnyRef是引用类型的基本类型,即java.lang.Object几乎任何类型class.
Any是AnyVal和之间的共同类型AnyRef.在你的榜样,你回来1 else false,所以编译器查找之间的普通型Int和Boolean,发现AnyVal.
如果你返回if(true) 1 else "hello",它会找到Int(an AnyVal)和String(an AnyRef)之间的公共类型,所以它找到了Any.