Is there any reason I don't know of why the follow...
# getting-started
h
Is there any reason I don't know of why the following would be inferior to a standard class and constructors? (it is superior in flexibility)
Copy code
interface 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?
r
Ultimately it will get compiled down to a separate class definition (with a funky name). A good reason to separate (in my opinion) is to not have an entire class definition in a function, but that's probably just a matter of taste.
h
i think i prefer this approach to open classes
plus, you can always implement multiple interfaces, so they're just way more flexible
r
You don't need open classes. You could use a construct like this:
Copy code
interface 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
Copy code
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 APIs
h
yeah, so I guess the other aspect of taste here is that I don't want my code filled with various names for the same thing like
BasicFoo
,
FooInterface
,
FooImplementation
, etc
r
Of course you can replicate this with functions and object expressions as well:
Copy code
interface Foo { ... }
interface MutableFoo : Foo { ... }
private fun makeFoo(...) : MutableFoo = object : MutableFoo { ... }
fun Foo(...): Foo = makeFoo(...)
fun MutableFoo(...): MutableFoo = makeFoo(...)
h
yeah, and that's how lists are written, basically, except the functions are masquerading as constructors, using constructor naming convention
r
Not really. Lists are closer to my first example, but they delegate to platform types (
ArrayList
on the JVM).