Anyone got any tips on abstracting over an `is` ch...
# getting-started
r
Anyone got any tips on abstracting over an
is
check and smart cast in a
when
statement? Problem in thread...
It doesn't take a coding genius to spot the duplication here, but I'm struggling to work out how to pull out a parameterised method to get rid of it...
a
it looks like you just need need to make the function generic, so Json Object/Array/String is passed in as
T
.
Copy code
inline fun <reified T> fetch(key: String): Outcome<FailedLookupResult, T> =
  ifContains(key) {
    when (val candidate = get(key)) {
      is T -> candidate.success()
      null -> NullValue(key).failure()
      else -> UnexpectedType(key, candidate).failure()
    }
  }
(Using
reified
might not be necessary - I can’t remember off the top of my head)
r
Oh, so you can... thanks! That's embarrassing, should have been able to work that out on my tod.
👍 1
a
I just had to mess around with generics & reified so it’s fresh in my mind :)
m
Maybe if the Json.* classes have some common ancestor (ie JsonNode) I would add an upper bound for better type safety
T:JsonNode
@Adam S reified is needed only if you need to access
T
inside the function, so I'd say yes in this case it's mandatory
👍 1