对一个变量看似多余的重新指定感到困惑';s在泛型scala函数中的类型
我很好奇为什么我能够像这样将类型参数化参数的类型重新声明给scala函数:对一个变量看似多余的重新指定感到困惑';s在泛型scala函数中的类型,scala,generics,types,Scala,Generics,Types,我很好奇为什么我能够像这样将类型参数化参数的类型重新声明给scala函数: // original def ident[T](z:T) = z def echo[T](x:T) = { ident(x) } echo("hi") 其行为与此完全相同: // modified with what seems to be a useless re-specification of the original type def ident[T](z:T) = z def echo[
// original
def ident[T](z:T) = z
def echo[T](x:T) = {
ident(x)
}
echo("hi")
其行为与此完全相同:
// modified with what seems to be a useless re-specification of the original type
def ident[T](z:T) = z
def echo[T](x:T) = {
ident(x:T) // <<< --- we specify type 'T' here, but not in the orig
}
echo("hi")
//修改为原始类型的无用重新规范
定义标识[T](z:T)=z
def回波[T](x:T)={
标识(x:T)//它被称为类型归属。它类似于类型转换,但并不完全相同。也就是说,如果类型不兼容,则会出现编译器错误。因此,这也类似于类型检查。如果你说x:T
,你告诉编译器你希望x
是T
。如果x
是T
,那么它就是一个T
我将被视为一个确切的T
它有何用处?您可以使用它向上投射底部类型,如null
:
ident(null: T)
或者简单地向上投射一些非空对象
在你问题的上下文中,归属没有任何作用。我们已经知道x
是T
。但是如果我们试图用其他东西来做这件事
class Z
scala> def test[T](t: T): T = { val z = new Z; ident(z: T) }
<console>:9: error: type mismatch;
found : z.type (with underlying type Z)
required: T
def test[T](t: T): T = { val z = new Z; ident(z: T) }
^
谢谢!我现在未经批准。而且,我发现这个帖子也非常有用>
scala> val x = 1: Short
x: Short = 1
scala> val x = 1: Long
x: Long = 1
scala> val l = Nil: List[Int]
l: List[Int] = List()