“ def apply [T](c:T)”和“ type T; def apply(c:T)”之间有什么区别

时间:2019-12-03 00:39:41

标签: scala generics types type-inference type-members

我有这个程序:

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

那我为什么不能写

type T

def apply(c:T)

似乎与

相同
apply[T](c:T)

我写的时候T是什么类型

val d=B{println(1);2}

我可以在这里写很多行!

因为T表示泛型,所以它可以是Int,String,用户定义的类Apple,Orange ...

什么是

println(1);2

是否存在“代码行”类型?

谢谢!

1 个答案:

答案 0 :(得分:1)

块的类型是该块上最后一个表达式的类型。所以

{ println(...); 2 } 

具有类型Int

BC之间的差异是类型成员和类型参数(12)之间类型推断的差异。

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仍然是抽象

Use of abstract type in a concrete class?

Concrete classes with abstract type members

在Scala中有关于类型推断的论文:

Plociniczak,休伯特;马丁·奥德斯基。解密本地类型推断 https://infoscience.epfl.ch/record/214757

如果您希望e进行编译,则可以指定T

val e: Unit = C.asInstanceOf[C.type{type T = Int}]{println(1);2}