Actually I've stuck with functional programming code style and project structure. When programming in Java I knew where to place all my logic, but I'm not familiar with the functional style.
Actually I try to make my Scala classes in my current project immutable. Then I want to use scalaz.Lens and scalaz.PLens to change my objects in future(actually create new).
In all Lense examples people place a code in one object, which extends App trait to simply show how it works. But in real-life example should be some appropriate place to write those Lenses.
In Java all mutators and accessors placed in classes itself. But with Lenses I don't know where to write them.
Will appreciate any advice
Typically lenses are hold in companion objects, like
package package1
import monocle.Iso
import monocle.macros.Lenses
@Lenses
case class Name(first: String, last: String, mid: Option[String]) {
def fullName = s"$first ${mid.fold("")(_ + " ")}$last"
}
object Name {
val fullName = Iso[Name, String](_.fullName)(_.split(' ') match {
case Array() => Name("", "", None)
case Array(name) => Name(name, "", None)
case Array(first, last) => Name(first, last, None)
case Array(first, mid, last, _*) => Name(first, last, Some(mid))
})
}
and
package package2
import monocle.macros.Lenses
import package1._
@Lenses
case class User(name: Name, age: Int)
object User {
val fullName = name ^<-> Name.fullName
}
Here the @Lenses
macro annotation will automatically put lenses for simple fields in companion objects
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With