Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

this inside on constructor  RSS feed

 
ekte spiriopoulos
Ranch Hand
Posts: 217
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
 
Henry Wong
author
Sheriff
Posts: 23283
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

The this reference can be used for an object to reference itself, even before instantiation is complete. Be careful though. There is an initialization order, and some stuff may not be initialized yet.

All in all, the way that it is used in the constructor (in your example), is pretty much the same usage for methods too.

Henry
 
Dave Tolls
Rancher
Posts: 2914
36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Without the 'this' then that line would be assigning the value of the 'numberfood' parameter to itself, and not the member attribute of the class.
Using 'this' tells the compiler that you want to assign the value passed into the constructor to the class attribute.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!