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?
Unit in Kotlin corresponds to the void in Java. Like void, Unit is the return type of any function that does not return any meaningful value, and it is optional to mention the Unit as the return type. But unlike void, Unit is a real class (Singleton) with only one instance.
In Kotlin, You can pass a variable number of arguments to a function by declaring the function with a vararg parameter. a vararg parameter of type T is internally represented as an array of type T ( Array<T> ) inside the function body.
Kotlin gives us the power to declare high-order functions. In a high-order function, we can pass and return functions as parameters.
The core concept in Kotlin is the same. An annotation allows you to associate additional metadata with a declaration. The metadata can then be accessed by tools that work with source code, with compiled class files, or at runtime, depending on how the annotation is configured.
You can just do
fun testMethod(inst: Base) {
inst.method()
}
Since both DervA
and DervB
are Base
s, 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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With