Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

`this` Type in Scala

Tags:

scala

Looking at this question, Fill immutable map with for loop upon creation, I was curious as to what this means in 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?

like image 598
Kevin Meredith Avatar asked Nov 01 '22 03:11

Kevin Meredith


1 Answers

It seems to work a bit odd in the REPL, but if you actually compile or interpret a script, this does indeed seem to point to the current instance of the enclosing 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 for why it does not exhibit this behavior in the REPL, I'm not sure.

like image 52
KChaloux Avatar answered Nov 15 '22 05:11

KChaloux