Sembra un po 'strano nel REPL, ma se si compila o interpreta effettivamente uno script, this
sembra infatti puntare all'istanza corrente dell'oggetto che lo racchiude.
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
}
}
Per quanto riguarda il motivo per cui non presenta questo comportamento nella REPL, non sono sicuro.
+1, perché anche se inizialmente pensavo che sarebbe stata una semplice risposta "è solo un riferimento allo scopo attuale", sono stato completamente in grado di capire che cosa è per me stesso. Questo non è aiutato da quanto sia difficile per google ciò che "questo" è in Scala. – KChaloux