On Kotlin, Arguments of a function require their type annotation when defining the method.
In my case, I have two classes from an interface.
interface Base{ fun method() } class DervA():Base{ fun override method(){ ... } } class DervB():Base{ fun override method(){ ... } } And, I hope to call their methods from other function like
fun test_method(inst){ inst.method() } But, Kotlin compiler complains "a type annotation is required on a value parameter" .
Should I define "test_method" for each of the classes ?
fun test_method_for_DervA(inst:DervA){ inst.method() } fun test_method_for_DervB(inst:DervB){ inst.method() } Do you have any smarter way for it?
23 Answers
You can just do
fun testMethod(inst: Base) { inst.method() } Since both DervA and DervB are Bases, they can also be passed to testMethod and their overridden method will be called. That's one of the fundamental principles of OOP.
Note that if method and testMethod have the same return type, you can shorten it to
fun testMethod(inst: Base) = inst.method() 4fun test_method(inst){ inst.method() } What, in your opinion, could help the compiler derive the type of inst and decide whether inst even has .method()?
I suppose you need inst: Base declared somewhere for inference to work.
Your method signature isn't correct, the compiler doesn't have a chance to know the parameter's type, there's no inference available in this situation:
fun test_method(inst) It's necessary to declare it like this:
fun test_method(inst: Base)