Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare a nullable function Parameter in kotlin

Tags:

kotlin

For example:

fun f(func: () -> Any?)

Parameter func means a function which returns Any? type. But how to make func nullable like:

fun f( (func: () -> Any?)? )
like image 511
FredSuvn Avatar asked Jun 25 '18 01:06

FredSuvn


People also ask

How do you handle nullable in Kotlin?

Kotlin has a safe call operator (?.) to handle null references. This operator executes any action only when the reference has a non-null value. Otherwise, it returns a null value. The safe call operator combines a null check along with a method call in a single expression.

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.

How do I declare a function in Kotlin?

To define a function in Kotlin, fun keyword is used. Then comes the name of the function (identifier). Here, the name of the function is callMe . In the above program, the parenthesis ( ) is empty.

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.


1 Answers

You are not too far away, I think you just misplaced the parentheses.

Try with:

fun f(func: (() -> Any?)?)
like image 96
crgarridos Avatar answered Oct 16 '22 09:10

crgarridos