like some people do
someFunctionThatRequiresInterfaceTypeAsArgument(interface()
{
override bool getRandomBoolean()
{
return Random.nextBool()
}
})
etc. is there a way to do this same thing in kotlin without creating a new class from this interface?
1 Like
kyay10
2
someFunctionThatRequiresInterfaceTypeAsArgument(object : InterfaceName
{
override bool getRandomBoolean()
{
return Random.nextBool()
}
})
1 Like
Sure, you can use object
expression to implement the interface anonymously:
import kotlin.random.Random
fun someFunctionThatRequiresInterfaceTypeAsArgument(foo: MyInterface) = println(foo.getRandomBoolean())
//sampleStart
interface MyInterface {
fun getRandomBoolean(): Boolean
}
fun main() {
someFunctionThatRequiresInterfaceTypeAsArgument(object: MyInterface {
override fun getRandomBoolean() = Random.Default.nextBoolean()
})
}
//sampleEnd
Additionally, if your interface has exactly one method, you can define it as a fun interface
and implement like that:
import kotlin.random.Random
fun someFunctionThatRequiresInterfaceTypeAsArgument(foo: MyInterface) = println(foo.getRandomBoolean())
//sampleStart
fun interface MyInterface {
fun getRandomBoolean(): Boolean
}
fun main() {
someFunctionThatRequiresInterfaceTypeAsArgument(MyInterface { Random.Default.nextBoolean() })
}
//sampleEnd
2 Likes