`这是Scala中的`类型

`这是Scala中的`类型,scala,Scala,看着这个问题,我很好奇这在Map(1->this)中是什么意思 我以前从未见过type作为一种类型 这是什么?它在REPL中的工作似乎有点奇怪,但是如果您实际编译或解释脚本,这确实似乎指向封闭对象的当前实例 import scala.reflect.runtime.{ universe => ru } object Main { def getType[T : ru.TypeTag](instance: T) = ru.typeOf[T] def sayHello = prin

看着这个问题,我很好奇这在
Map(1->this)
中是什么意思

我以前从未见过
type
作为一种类型


这是什么?

它在REPL中的工作似乎有点奇怪,但是如果您实际编译或解释脚本,
这确实似乎指向封闭对象的当前实例

import scala.reflect.runtime.{ universe => ru }

object Main {
  def getType[T : ru.TypeTag](instance: T) = ru.typeOf[T]

  def sayHello = println("hello!")

  def main(args: Array[String]): Unit = {
    println(this.getType(123)) // Prints "Int"
    this.sayHello              // Prints "hello!" to the console

    getType(this).decls foreach println _
    // Prints the following outputs to the console:
    // constructor Main
    // method getType
    // method sayHello
    // method main
  }
}

至于为什么它在REPL中没有表现出这种行为,我不确定。

+1,因为虽然我最初认为这是一个简单的“它只是对当前范围的引用”答案,但我已经完全能够弄清楚它对我自己来说是什么。对于谷歌来说,Scala中的“This”是多么困难,这并没有帮助。“至于为什么它在REPL中没有表现出这种行为,我不确定”。是的。尝试将代码粘贴到REPL中,然后执行
Main.Main(Array.empty)
,您将得到相同的结果(换句话说,
thid
也将引用REPL中的
Main
)。但是,如果您在REPL中的顶级声明中引用
this
,那么
this
实际上将引用封闭的类/对象,在这种情况下,它恰好是REPL创建的一个包装器对象,用于承载您的声明(请参阅)至于
类型的来源,my(纯推测性)猜测它来自尝试清理实际类型的REPL。因为代码在一个名为
$iw
的包装器对象中,当您在repl中声明一个class/trait
Foo
时,实际的类型将类似于
iw.Foo
,但您确实不想知道
$iw
,因此repl删除
$iw
前缀并只打印
Foo
。在OP的例子中,
这个
的类型是
$iw.type
,因此删除
$iw
只会留下
类型
,不幸的是,这不是实际的类型。所以,这只是REPL试图对你们友好的一个极端情况。
import scala.reflect.runtime.{ universe => ru }

object Main {
  def getType[T : ru.TypeTag](instance: T) = ru.typeOf[T]

  def sayHello = println("hello!")

  def main(args: Array[String]): Unit = {
    println(this.getType(123)) // Prints "Int"
    this.sayHello              // Prints "hello!" to the console

    getType(this).decls foreach println _
    // Prints the following outputs to the console:
    // constructor Main
    // method getType
    // method sayHello
    // method main
  }
}