Skip to content

Commit

Permalink
no message
Browse files Browse the repository at this point in the history
  • Loading branch information
FuadEfendi committed Apr 20, 2023
1 parent 55c32e4 commit a3a16a4
Showing 1 changed file with 10 additions and 0 deletions.
10 changes: 10 additions & 0 deletions content/docs/scala/underscore/index.md
Expand Up @@ -34,3 +34,13 @@ authors:
`++` does concatenation for sequences. `.reduce(_++_)` concatenates a list of sequences together. You can also use `flatten` for that.


## Scala `_=` vs. classic Java "getters" and "setters"

Functional Programming (FP) discourages data structures that maintain state, so Scala style tries to avoid setters whenever possible.

Getters and setters (if you define mutable property with `var`) are automatically created in Scala and seamlessly used. Java does not have this so you need to create them manually.

Scala already automatically creates getters and setters for fields. This is because fields are never actually public. Instead, all fields are private, and a getter `def <fieldname>: <fieldtype>` is created. A setter `def <fieldname>_=(new: <fieldtype>): Unit` is created if the field is var. Because the getter method has no parameter lists, its usage looks like a Java field access (`myObject.myProperty`), though it isn't. Scala also introduces sugar for methods that end in `_=`, allowing them to be called with `myObject.myProperty = newValue` notation. This is the same as `myObject.myProperty_=(newValue)`. You can manually create methods like this and see the same behavior. (Caveat: a manually defined method `x_=` will not sugar unless a getter`x` is also present.)

The function of (Boolean)BeanProperty is to simply add aliases to these methods named in the standard Java Bean way (getX/isX and setX). Therefore, they are unnecessary for pure Scala, but are useful if you need to conform to the Java standard for some reason. E.g. you use some library that reflectively accesses a bean's properties.

0 comments on commit a3a16a4

Please sign in to comment.