-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path23_meta.clj
More file actions
53 lines (42 loc) · 1.56 KB
/
23_meta.clj
File metadata and controls
53 lines (42 loc) · 1.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
(ns koans.23-meta
(:require [koan-engine.core :refer :all]))
(def giants
(with-meta 'Giants
{:league "National League"}))
(meditations
"Some objects can be tagged using the with-meta function"
(= {:league "National League"} (meta giants))
"Or more succinctly with a reader macro"
(= {:division "West"} (meta '^{:division "West"} Giants))
"While others can't"
(= "This doesn't implement the IObj interface"
(try
(with-meta
2
{:prime true})
(catch ClassCastException e
"This doesn't implement the IObj interface")))
"Notice when metadata carries over"
(= {:foo :bar}
(meta (merge '^{:foo :bar} {:a 1 :b 2} {:b 3 :c 4})))
"And when it doesn't"
(= nil (meta (merge {:a 1 :b 2}
'^{:foo :bar} {:b 3 :c 4})))
"Metadata can be used as a type hint to avoid reflection during runtime"
(= \C (#(.charAt ^String % 0) "Cast me"))
"You can directly update an object's metadata"
(= 8 (let [giants
(with-meta
'Giants
{:world-series-titles (atom 7)})]
(swap! (:world-series-titles (meta giants)) inc)
@(:world-series-titles (meta giants))))
"You can also create a new object from another object with metadata"
(= {:league "National League" :park "AT&T Park"}
(meta (vary-meta giants
assoc :league "National League" :park "AT&T Park")))
"But it won't affect behavior like equality"
(= 'Giants
(vary-meta giants dissoc :league))
"Or the object's printed representation"
(= "Giants" (pr-str (vary-meta giants dissoc :league))))