https://kotlinlang.org logo
Title
y

y

03/23/2023, 5:23 PM
I've got something like
interface MyInterface<R> {
    fun doIt(): R
}

object MyImpl : MyInterface<String> {
    override fun doIt(): String = "hello"
}

object MyOtherImpl : MyInterface<Int> {
    override fun doIt(): Int = 5
}
which works fine. now say I've got
fun <R> foo(impl: MyInterface<R>): R = impl.doIt()
is it possible to add a default value to
impl
?
fun <R> foo(impl: MyInterface<R> = MyImpl) = impl.doIt()
doesn't compile. the best I could come up with is to also add an overload of `foo`:
fun foo() = foo(MyImpl)
.
p

Paul Griffith

03/23/2023, 5:25 PM
the overload is your only option afaik
l

Loney Chou

03/23/2023, 5:27 PM
MyImpl
emits
String
, while
MyInterface<R>
emits
R
,
R
could be something other than
String
, so you can't assign
impl: MyInterface<R>
with
MyImpl
.
Maybe you're thinking of default type parameter, but that's not a thing in Kotlin.
y

y

03/23/2023, 5:31 PM
maybe I am. I'm trying to emulate Rust's associated type.
that said, default parameters are of course not a thing over there.
anyway, the overload seems like a reasonable compromise