Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin function argument without type annotation

Tags:

kotlin

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?

like image 731
ric Avatar asked Nov 06 '17 16:11

ric


People also ask

What is () -> unit in Kotlin?

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.

How do you pass arguments in Kotlin?

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.

Can I pass a function as a parameter in Kotlin?

Kotlin gives us the power to declare high-order functions. In a high-order function, we can pass and return functions as parameters.

What is a type annotation in Kotlin?

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.


1 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()
like image 195
Ruckus T-Boom Avatar answered Nov 08 '22 05:11

Ruckus T-Boom