Skip to content

Commit 764cac0

Browse files
author
Roman Janusz
committed
added some docs to TypedMap
1 parent 4e5e50f commit 764cac0

File tree

1 file changed

+45
-2
lines changed

1 file changed

+45
-2
lines changed

commons-core/src/main/scala/com/avsystem/commons/misc/TypedMap.scala

Lines changed: 45 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,59 @@
1-
package com.avsystem.commons
2-
package misc
1+
package com.avsystem.commons.misc
32

3+
import com.avsystem.commons.SharedExtensions._
44
import com.avsystem.commons.misc.TypedMap.GenCodecMapping
55
import com.avsystem.commons.serialization._
66

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+
*/
747
class TypedMap[K[_]](val raw: Map[K[_], Any]) extends AnyVal {
848
def apply[T](key: K[T]): T =
949
raw(key).asInstanceOf[T]
1050

1151
def get[T](key: K[T]): Option[T] =
1252
raw.get(key).asInstanceOf[Option[T]]
1353

54+
def getOpt[T](key: K[T]): Opt[T] =
55+
raw.getOpt(key).asInstanceOf[Opt[T]]
56+
1457
def getOrElse[T](key: K[T], defaultValue: => T): T =
1558
get(key).getOrElse(defaultValue)
1659

0 commit comments

Comments
 (0)