Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapped types in Scala

Is there a way to derive a type from an existing one in Scala?

For example, for case class Person(name: String, age: Int) I'd like to get a Product/Tuple of (Option[String], Option[Int]), i.e. a type mapped from an existing one.

There's a feature in Typescript (mapped types) that allows this relatively easily, which is how I started thinking down this path. But I'm not sure how something like this would be done in Scala.

I feel like the solution involves using shapeless in some way but I'm not sure how to get there.

like image 779
Alan Thomas Avatar asked Apr 16 '19 04:04

Alan Thomas


People also ask

What is a mapped object type?

A mapped type is a generic type which uses a union of PropertyKey s (frequently created via a keyof ) to iterate through keys to create a type: type OptionsFlags < Type > = { [ Property in keyof Type ]: boolean; };

What is map string string in Scala?

A map represents an mapping from keys to values. The Scala Map type has two type parameters, for the key type and for the value type. So a Map[String, Int] maps strings to integers, while a Map[Int, Set[String]] maps integers to sets of strings. Scala provides both immutable and mutable maps.

How do you access map elements in Scala?

Scala Map get() method with exampleThe get() method is utilized to give the value associated with the keys of the map. The values are returned here as an Option i.e, either in form of Some or None. Return Type: It returns the keys corresponding to the values given in the method as argument.


1 Answers

I'd suggest parameterize the type as follows:

case class Person[F[_]](name: F[String], age: F[Int])

And then you can derive types you want, like

import cats.Id

type IdPerson = Person[Id]
type OptPerson = Person[Option]

Where cats.Id is simply defined as type Id[A] = A. It is straightforward to write your own, but I suggest using cats' one since it comes with useful typeclass instances.

like image 142
Some Name Avatar answered Sep 21 '22 13:09

Some Name