Where to place Scala Lenses in my project?

In fact, I adhered to the functional style of the programming code and the structure of the project. When programming in Java, I knew where to put all my logic, but I am not familiar with the functional style.

Actually, I am trying 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 the future (actually create a new one).

In all Lense examples, people put code in a single object, which extends the features of the application to just show how it works. But in real life, an example should be the right place to record these lenses.

In Java, all mutators and accessors located in the classes themselves. But with lenses, I don’t know where to write them.

Understand any advice

+4
source share
1 answer

Typically, lenses are held in related objects, for example

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 annotation @Lenseswill automatically place lenses for simple fields in companion objects

+7
source

Source: https://habr.com/ru/post/1615761/


All Articles