Hi everyone, I'm trying to remove a duplication of...
# announcements
a
Hi everyone, I'm trying to remove a duplication of this code:
Copy code
.filter { _key, value ->
            value.getTimestamp().isBefore(Instant.now().plusSeconds(600))
        }
key
is a string but I don't care what type it is
value
can be multiple types but all implement the getTimestamp method that returns an instant, so I've tried tried to create a file like this:
Copy code
interface DataWIthTimestamp {
    fun getTimestamp(): Instant
}

val filterFutureData: (key: Any, value: DataWIthTimestamp) -> Boolean = { _, value ->
    value.getTimestamp().isBefore(Instant.now().plusSeconds(600))
}
which doesn't work as it says
Copy code
Type mismatch.
Required: Predicate<in String!, in Metric!>!
Found: (Any, DataWIthTimestamp) → Boolean
I know my implementation might not make sense 🙂
n
In order to make this work the way you'd want, for starters, you'd need to have some common interface that specifies
getTimestamp
that all the types you want it to work with, implement
value
 can be multiple types but all implement the getTimestamp method that returns an instant, so I've tried tried to create a file like this:
fkjdf
arg
Anyhow, the point is Kotlin cannot do anything with that information unless you either a) implement the function for every single type value can be, or b) all of those types inherit from some common interface
a
Oh, so they have to specifically implement that interface? just because those types are generated by avro and outside of my control
n
Right, so if those types are out of your control and don't implement an interface, then the best you can do is to factor out the rest of it into a function
a
a) is there, all those types I'll use the predicate in will implement the getTimestamp method
I've created the interface just to use it in the filterFutureData predicate
n
No, I mean you need to implement filterFutureDate
separately
for every type
unless they have a common base
Either that or maybe do some reflection god-awful stuff but you probably don't want to do that
a
oh ok got it, so that'll still make me write that predicate once per type
n
yeah
a
thanks for helping @Nir I think I'll just use it directly as I only use it once per type
n
I don't know all your circumstances but I'd guess that what makes sense, assuming they all use the same timestamp type
is to just factor out hte function starting from that point
Copy code
fun filterFutureDate(value: Timestamp) = value.isBefore(Istant.now().plusSeconds(600))
and now you could at least do
Copy code
.filter { _, value -> filterFutureDate(value.getTimestamp()) }
or maybe write it as an extension function on timestamp instead, so you can write
value.getTimestamp().filterFutureDate()
etc
a
oh ok that might be doable too, thanks a lot!