|
1 | | -package com.avsystem.commons |
2 | | -package misc |
| 1 | +package com.avsystem.commons.misc |
3 | 2 |
|
| 3 | +import com.avsystem.commons.SharedExtensions._ |
4 | 4 | import com.avsystem.commons.misc.TypedMap.GenCodecMapping |
5 | 5 | import com.avsystem.commons.serialization._ |
6 | 6 |
|
| 7 | +/** |
| 8 | + * A map whose keys are parameterized with value type. |
| 9 | + * This makes it possible to associate different value type with each key, in a type-safe way. |
| 10 | + * |
| 11 | + * [[TypedMap[K]]] has a [[GenCodec]] instance as long as there is a `GenCodec[K[_]]` instance for the key |
| 12 | + * type and a [[GenCodecMapping[K]]] instance that determines the codec for the value type associated with given |
| 13 | + * key. |
| 14 | + * |
| 15 | + * Example: |
| 16 | + * {{{ |
| 17 | + * sealed abstract class AttributeKey[T](implicit val valueCodec: GenCodec[T]) |
| 18 | + * extends TypedKey[T] with AutoNamedEnum |
| 19 | + * |
| 20 | + * object AttributeKey extends NamedEnumCompanion[AttributeKey[_]] { |
| 21 | + * object StringKey extends AttributeKey[String] |
| 22 | + * object IntKey extends AttributeKey[Int] |
| 23 | + * |
| 24 | + * val values: List[AttributeKey[_]] = caseObjects |
| 25 | + * } |
| 26 | + * |
| 27 | + * val attributes = TypedMap[AttributeKey]( |
| 28 | + * AttributeKey.StringKey -> "foo", |
| 29 | + * AttributeKey.IntKey -> 42, |
| 30 | + * ) |
| 31 | + * }}} |
| 32 | + * |
| 33 | + * Note that since all keys and value types are known statically, |
| 34 | + * the map above is somewhat equivalent to a case class: |
| 35 | + * |
| 36 | + * {{{ |
| 37 | + * case class Attributes( |
| 38 | + * string: Opt[String], |
| 39 | + * int: Opt[Int] |
| 40 | + * ) |
| 41 | + * }}} |
| 42 | + * |
| 43 | + * [[TypedMap]] might be a good choice if there is a lot of attribute keys, they aren't statically known or some |
| 44 | + * collection-like behaviour is necessary (e.g. computing the size, iterating over all elements). A [[TypedMap]] |
| 45 | + * is also easier to evolve than a case class (e.g. because of binary compatibility issues). |
| 46 | + */ |
7 | 47 | class TypedMap[K[_]](val raw: Map[K[_], Any]) extends AnyVal { |
8 | 48 | def apply[T](key: K[T]): T = |
9 | 49 | raw(key).asInstanceOf[T] |
10 | 50 |
|
11 | 51 | def get[T](key: K[T]): Option[T] = |
12 | 52 | raw.get(key).asInstanceOf[Option[T]] |
13 | 53 |
|
| 54 | + def getOpt[T](key: K[T]): Opt[T] = |
| 55 | + raw.getOpt(key).asInstanceOf[Opt[T]] |
| 56 | + |
14 | 57 | def getOrElse[T](key: K[T], defaultValue: => T): T = |
15 | 58 | get(key).getOrElse(defaultValue) |
16 | 59 |
|
|
0 commit comments