1

I am wondering if there is a way to accomplish the work that Partial<T> does in TypeScript in scala.

Specifically, for a given case class like

case class Foo(a: String, b: String, c: String)

Is there a way to derive a case class like

case class PartialFoo(a: Option[String], b: Option[String], c: Option[String])

in a way that I could construct a PartialFoo without having to declare it?

kheck
  • 57
  • 5
  • 1
    You could do something like: `final case class BaseFoo[F[_]](a: F[String], b: F[String], c: F[String])` and then `type Foo = BaseFoo[Id]` & `type PartialFoo = BaseFoo[Option]`. – Luis Miguel Mejía Suárez Feb 12 '21 at 22:48
  • 1
    Take a look at the `shapeless` library. But barring the dark magic in that library/macros, no. Scala generally does not have compile-time mechanisms for taking types apart to their fields and making new ones. – HTNW Feb 12 '21 at 23:09
  • I'm also dubious on why one would ever need a record type where every field is optional. – Levi Ramsey Feb 13 '21 at 00:14
  • 2
    Maybe trying to merge two case classes using upsert semantics. Perhaps trying to emulate https://stackoverflow.com/questions/171251/how-can-i-merge-properties-of-two-javascript-objects-dynamically. Interesting snippet by Krzysztof might be of interest [Generically update case class using another case class with Shapeless](https://gist.github.com/katlasik/a9309e310c220827552e99d60bb92866) – Mario Galic Feb 13 '21 at 00:36
  • @LeviRamsey this question is geared towards succinct syntax for use in unit testing. I have some classes that interact/relate on just a few fields. I want to test code that joins/relates those fields, but don't want the unit tests to have to dilute intent/readability on filling in dozens of unrelated fields. This is a pretty unique situation involving spark DataFrames, but I find this case illuminating in regards to learning scala and its abilities – kheck Feb 13 '21 at 01:24
  • Another use case would be SQL and GraphQL, e.g.: `SELECT name, address FROM people` `SELECT name, address, birthdate FROM people` https://stackoverflow.com/questions/59727388/mapped-types-in-scala-similar-to-typescript-pick-exclude-etc#comment123874563_59727388 – Richard Michael Coo Feb 26 '22 at 05:18

0 Answers0