"def apply [T](c:T)"和"def apply [T](c:T)"之间的区别是什么?和“类型T; def apply(c:T)". [英] What's different between "def apply[T](c:T)" and "type T;def apply(c:T)"
问题描述
我有这个程序:
object B{
def apply[T](c:T)={}
}
object C{
type T
def apply(c:T)={}
}
object A extends App{
val d=B{println(1);2}
val e=C{println(1);2}
}
线
val e = C{println(1);2}
告诉我错误:类型不匹配,预期C.T,实际:2
told me error:Type mismatch,expected C.T,actual:2
那我为什么不能写
type T
def apply(c:T)
似乎与
apply[T](c:T)
我写的时候T是什么类型
and what's the type of T when I write
val d=B{println(1);2}
我可以在这里写很多行!
I can write many lines here!
因为T表示泛型,所以它可以是Int,String,用户定义的类Apple,Orange ...
because T means generic,so it can be Int,String,user defined class Apple,Orange...
什么是
println(1);2
是否存在代码行"类型?
is there a type "lines of codes"?
谢谢!
推荐答案
块的类型是该块上最后一个表达式的类型.所以
The type of a block is the type of the last expression on the block. So
{ println(...); 2 }
具有类型Int
.
B
和C
之间的差异是类型成员和类型参数之间的类型推断差异( 2 )
Difference between B
and C
is difference in type inference between type members and type parameters (1, 2).
object B{
def apply[T](c:T)={}
}
object C{
type T
def apply(c:T)={}
}
class C1[T]{
def apply(c:T)={}
}
val d: Unit = B{println(1);2}
// val e: Unit = C{println(1);2} // doesn't compile
val e1: Unit = (new C1){println(1);2}
// scalacOptions ++= Seq("-Xprint:typer", "-Xprint-types")
// val d: Unit = A.this{A.type}.B.apply{[T](c: T)Unit}[Int]{(c: Int)Unit}({
// scala.Predef.println{(x: Any)Unit}(1{Int(1)}){Unit};
// 2{Int(2)}
// }{2}){Unit};
// val e: Unit = A.this{A.type}.C.apply{(c: A.C.T)Unit}({
// println{<null>}(1{Int(1)}){<null>};
// 2{Int(2)}
// }{<null>}){<error>};
// val e1: Unit = new A.C1[Int]{A.C1[Int]}{()A.C1[Int]}(){A.C1[Int]}.apply{(c: Int)Unit}({
// scala.Predef.println{(x: Any)Unit}(1{Int(1)}){Unit};
// 2{Int(2)}
// }{2}){Unit};
在C
类型中,T
仍然是抽象
在Scala中有关于类型推断的论文:
There is thesis about type inference in Scala:
Plociniczak,休伯特;马丁·奥德斯基.解密本地类型推断 https://infoscience.epfl.ch/record/214757
如果要编译e
,则可以指定T
If you want e
to compile you can specify T
val e: Unit = C.asInstanceOf[C.type{type T = Int}]{println(1);2}
这篇关于"def apply [T](c:T)"和"def apply [T](c:T)"之间的区别是什么?和“类型T; def apply(c:T)".的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!