`this`输入Scala

Kev*_*ith 5 scala

看看这个问题,在创建时用for循环填充不可变地图,我很好奇是什么this意思Map(1 -> this).

scala> Map(1 -> this)
res6: scala.collection.immutable.Map[Int,type] = Map(1 -> @53e28097)

scala> res6(1)
res7: type = @53e28097
Run Code Online (Sandbox Code Playgroud)

我之前没有见过type作为一种类型.

它是什么?

KCh*_*oux 2

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

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
  }
}
Run Code Online (Sandbox Code Playgroud)

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