Hullaballoonatic
06/05/2019, 7:53 PMinterface Foo {
val a: Int
val b: Int
fun sum() = a + b
}
fun Foo(a: Int, b: Int) = object : Foo {
override val a = a
override val b = b
}
is it more expensive to instantiate object literals than class instances?Ruckus
06/05/2019, 7:59 PMHullaballoonatic
06/05/2019, 8:00 PMHullaballoonatic
06/05/2019, 8:01 PMRuckus
06/05/2019, 8:04 PMinterface Foo { ... }
private class FooImpl : Foo { ... }
fun Foo(...): Foo = FooImpl(...)
Which is basically what your example gets compiled down to. This has the advantage that you can also do something like
interface Foo { ... }
interface MutableFoo : Foo { ... }
private class FooImpl : Foo { ... }
fun Foo(...): Foo = FooImpl(...)
fun MutableFoo(...): MutableFoo = FooImpl(...)
You only need one implementation, but can expose different APIsHullaballoonatic
06/05/2019, 8:05 PMBasicFoo
, FooInterface
, FooImplementation
, etcRuckus
06/05/2019, 8:06 PMinterface Foo { ... }
interface MutableFoo : Foo { ... }
private fun makeFoo(...) : MutableFoo = object : MutableFoo { ... }
fun Foo(...): Foo = makeFoo(...)
fun MutableFoo(...): MutableFoo = makeFoo(...)
Hullaballoonatic
06/05/2019, 8:09 PMRuckus
06/05/2019, 8:11 PMArrayList
on the JVM).