`this` Enter Scala

Looking at this question, Fill an immutable map with a loop at creation , I was curious what this means Map(1 -> this) .

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

I have not seen type before as a type.

What is it?

+5
source share
1 answer

The REPL seems a little strange, but if you really compile or interpret the script, this really points to the current instance of the surrounding object.

 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 } } 

As to why this behavior does not show up in REPL, I'm not sure.

+2
source

All Articles