Fork me on GitHub
#code-reviews
<
2020-04-07
>
Eric Scott13:04:50

Is there a more idiomatic way to do this?

> (defn lang-tag [s tag]
   (with-meta (reify java.lang.Object (toString [this] s)) {:lang tag}))
lang-tag
> (def gaol (lang-tag "gaol" :en-uk))
gaol
> (str gaol)
"gaol"
> (meta gaol)
{:lang :en-uk}
> (def jail (lang-tag "jail" :en-us))
jail
> ;; etc

noisesmith15:04:40

@eric.d.scott one alternative

(defn lang-tag
  [s tag]
  ^{:long tag} (reify Object (toString [this] s)))

noisesmith15:04:01

Object (and most of java.lang) is already in scope, so doesn't need the full package

noisesmith15:04:29

typically I only use with-meta inside macros in order to emit a meta transform, the reader macro is much simpler otherwise

Eric Scott16:04:37

But the general idea of sticking metadata to a string by reifying Object with (toString...) is generally considered legit?

noisesmith16:04:42

yes, that's pretty much how it would need to be done

noisesmith16:04:00

if you need other operations, you would need to reify CharSequence or something instead...

noisesmith16:04:18

but it's probably better to own a string as a field than to try to be one

👍 4