Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to place Scala Lenses in my project?

Tags:

scala

lenses

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

like image 490
maret Avatar asked Mar 15 '23 04:03

maret


1 Answers

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

like image 162
Odomontois Avatar answered Mar 17 '23 04:03

Odomontois