janvladimirmostert
05/27/2023, 8:13 PMinterface NumberFactory {
fun create(): Int
}
class Something {
context(NumberFactory)
companion object {
fun generate(): Int {
return this@NumberFactory.create()
}
}
}
fun main() {
val number1 = object : NumberFactory {
override fun create(): Int {
return 1
}
}
val number2 = object : NumberFactory {
override fun create(): Int {
return 2
}
}
while (true) {
with(if (Random().nextBoolean()) {
number1
} else {
number2
}) {
Something.generate()
}.also(::println)
}
will we be seeing 1 and 2 in the above output or will it only be 1s the whole time (assuming the first factory picked by random is number1)?Youssef Shoaib [MOD]
05/27/2023, 9:30 PMclass Something {
companion object {
context(NumberFactory)
fun generate(): Int {
return this@NumberFactory.create()
}
}
}
Which is already supportedjanvladimirmostert
05/27/2023, 10:36 PMinterface NumberFactory {
fun create(): Int
}
interface Generator {
fun generate(): Int
}
class Something {
companion object : Generator {
context(NumberFactory)
override fun generate(): Int {
return this@NumberFactory.create()
}
}
}
unless you put the context on top of the generate in the interface too
I was exploring whether context on top of the companion object would somehow get into the companion functions, in other words
context(...) companion obect { fun f1() {} fun f2() {} }
would then be the same as
companion obect { context(...) fun f1() {} context(...) fun f2() {} }
Youssef Shoaib [MOD]
05/27/2023, 10:55 PMinterface Generator<in Ctx> {
context(Ctx) fun generate(): Int
}
So that anyone calling generate must either know what kind of context this generator wants and provide it, or they must ask the caller themselves to provide that context.