Scala Constructor Parameters -


what difference between private var constructor parameter , constructor parameter without val/var? same in terms of scope/visibility?

ex:

class person(private var firstname:string, lastname:string) 

yes, there 2 important differences. first easy one: constructor parameters without var or val keywords not mutable variables—their values can't changed in body of class.

even if restrict ourselves val keyword, though, there's still difference between private val , keyword-less parameters. consider following:

class person(private val firstname: string, lastname: string) 

if @ compiled class javap -v person, we'll see has 1 field, firstname. lastname constructor parameter, means may garbage-collected after class initialized, etc.

the compiler smart enough know when value of lastname needed after initialization, , create field in case. consider following variation:

class person(private val firstname: string, lastname: string) {   def fullname = firstname + " " + lastname } 

the compiler can tell may need value of lastname later, , if check javap again we'll see class has 2 fields (note if we'd defined fullname val instead of def, it'd have 1 field).

lastly, note if make firstname object-private instead of class-private, works plain old keyword-less constructor parameter:

class person(private[this] val firstname: string, lastname: string) 

this works var instead of val:

class person(private[this] var firstname: string, lastname: string) 

both of these classes have no fields. see section 5.2 of the language specification more details object-private access.


Comments

Popular posts from this blog

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

html - How to style widget with post count different than without post count -

url rewriting - How to redirect a http POST with urlrewritefilter -