Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
对一个变量看似多余的重新指定感到困惑';s在泛型scala函数中的类型_Scala_Generics_Types - Fatal编程技术网

对一个变量看似多余的重新指定感到困惑';s在泛型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[

我很好奇为什么我能够像这样将类型参数化参数的类型重新声明给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[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()