Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type of this in Scala

Is there a way to make a method to always return the type of the same class that called it ?

Let me explain:

class Shape {
  var mName: String = null
  def named(name: String): Shape = {
    mName = name
    this
  }
}

class Rectangle extends Shape {
  override def named(name: String): Rectangle = {
    super.named(name)
    this
  }
}

This works, but is there a way to do this without having to override the named function in all of my subclasses? I'm looking for something like this (which does not work):

class Shape {
  var mName: String = null
  def named(name: String): classOf[this] = { // Does not work but would be great
    mName = name
    this
  }
}

class Rectangle extends Shape {
}

Any idea ? Or is it not possible ?

like image 591
Mikaël Mayer Avatar asked Oct 24 '12 11:10

Mikaël Mayer


1 Answers

You need to use this.type instead of classOf[this].

class Shape {
  var mName: String = null
  def named(name: String): this.type = {
    mName = name
    this
  }
}

class Rectangle extends Shape {
}

Now to demonstrate that it works (in Scala 2.8)

scala> new Rectangle().named("foo")
res0: Rectangle = Rectangle@33f979cb

scala> res0.mName
res1: String = foo

this.type is a compile-type type name, while classOf is an operator that gets called at runtime to obtain a java.lang.Class object. You can't use classOf[this] ever, because the parameter needs to be a type name. Your two options when trying to obtain a java.lang.Class object are to call classOf[TypeName] or this.getClass().

like image 96
Ken Bloom Avatar answered Nov 13 '22 00:11

Ken Bloom