Reputation: 4425
In Kotlin I have an interface with default implementation:
interface MyInterface {
fun foo() = "foo"
fun bar() = 120
}
So I am trying to create a function that would expect as a parameter a MyInterface
or use the default implementation if one is not passed.
The following does not compile:
fun(param1: String, param2: Int, myInterface: MyInteface = MyInterface())
How can I fix this?
Upvotes: 0
Views: 139
Reputation: 18627
As other answers have said, you need an object which implements your interface.
Perhaps the simplest way of creating one is using the object : <ClassOrInterface>
syntax:
fun myFun(param1: String, param2: Int, myInterface: MyInterface = object : MyInterface{}) {
// …
}
That may create a new object for each call which uses the default*. If that matters, you might want to create an object separately:
val defaultImpl = object : MyInterface
fun myFun(param1: String, param2: Int, myInterface: MyInterface = defaultImpl) {
// …
}
(* Kotlin 1.3.50 always seems to create a new instance each time the default is used. But that behaviour isn't specified in the docs, so it could potentially be optimised in future releases.)
Upvotes: 1
Reputation: 2345
The default then needs to be an object which implements the interface...
class MyInterfaceImplementation: MyInterface
fun (param1: String, param2: Int, myInterface: MyInteface = MyInterfaceImplementation()) {
/* Function implementation */
}
Upvotes: 1
Reputation: 692231
Create a class that implements the interface, and use
class MyDefaultImplementation : MyInterface
fun(param1: String, param2: Int, myInterface: MyInterface = MyDefaultImplementation())
Or even better, create an object (singleton) that implements this interface, and use that object as default value.
object MyDefaultImplementationObject : MyInterface
fun(param1: String, param2: Int, myInterface: MyInterface = MyDefaultImplementationObject)
Upvotes: 2