【发布时间】:2014-07-06 16:22:14
【问题描述】:
我正在学习 Coursera 教授 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?它会返回 Any 吗?
【问题讨论】:
-
if (cond) 1 else "hello"。Any有两个子类型 -AnyVal和AnyRef,因此如果这两个分支分别返回一个子类型,则整个表达式的类型将是Any。 -
@Lee 这应该是一个答案
标签: scala inheritance hierarchy subtype