kotlinx-datetime icon indicating copy to clipboard operation
kotlinx-datetime copied to clipboard

Clock interface should be a "fun" interface

Open dalewking opened this issue 2 years ago • 4 comments

Since it is a SAM should be declared as a fun interface to allow using a lambda to provide an implementation.

dalewking avatar May 11 '23 15:05 dalewking

When an interface has a single abstract method, it doesn't automatically qualify to be a functional interface.

We can however consider providing a SAM-like constructor function for Clock, e.g.

fun Clock(instantProvider: () -> Instant): Clock

ilya-g avatar May 11 '23 19:05 ilya-g

That would be fine too. I am looking to use dependency injection to inject Clock instance into code and to be able to inject an instance that I can easily control.

What I am doing now is that I have:

class OverridableClock : Clock {
    var instant: Instant? = null
    override fun now() = instant ?: Clock.System.now()

    operator fun plusAssign(duration: Duration) {
        instant = now() + duration
    }
}

I guess though since you you have a companion object I can go ahead and create such a function as an extension.

dalewking avatar May 12 '23 06:05 dalewking

For what it's worth, requiring that Clock be a SAM would break proposals like #17 for very little benefit.

kevincianfarini avatar Dec 15 '23 00:12 kevincianfarini

For what it's worth, requiring that Clock be a SAM would break proposals like #17 for very little benefit.

Given that #17 seems to now be going the way of not changing Clock interface and #382 proposes moving Clock to the standard library, i once again propose that Clock be made a a fun interface.

Agreed it is a ver small benefit, but it also has basically zero cost

dalewking avatar May 08 '24 03:05 dalewking