下面的代码
object testType extends App {
def func(x:Int) = if(x==0) 1.0 else 'c'
println(func(0))
println(func(1))
}
结果
1.0
99.0
起初当我写这个的时候,我以为 Scala 不会允许这样的函数,但它把这个函数解释为 (Int) => Double
。这感觉就像类型强制。
如果我用 'c'
替换上面函数中的 "c"
,它实际上返回
1.0
c
函数现在被解释为 (Int) => Any
问题:如果 Scala 是强类型的,为什么第一个带有 'c'
的例子返回一个 Double 以及为什么 (Int) => Double
和 (Int) => 这两个例子有什么
吗?
最佳答案
Scala 中的类型之间存在一种关系,称为"weak conformance"。 . Char
弱符合 Double
(因为它弱符合 Int
而弱符合 Double
)。 if (<cond>) then <e1> else <e2>
的类型是defined to be the weak least upper bound (wlub) of types of <e1>
and <e2>
(对于具有许多分支的其他表达式也有类似的规则:match
和 try/catch
)。 Char
的wlub和 Double
是Double
; String
的 wlub和 Double
是Any
.
关于scala - 为什么 Scala 将类型从 Char 强制转换为 Double?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39525314/