Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing and using function as constructor argument in Kotlin

Tags:

android

kotlin

How to create a class that takes function as a constructor argument. Then, use this function at some later point in the class.

like image 842
n.arrow001 Avatar asked Jul 04 '17 19:07

n.arrow001


People also ask

How does Kotlin pass value in constructor?

The block of code surrounded by parentheses is the primary constructor: (val firstName: String, var age: Int) . The constructor declared two properties: firstName (read-only property as it's declared using keyword val ) and age (read-write property as it is declared with keyword var ).

Can you pass functions as parameters in Kotlin?

In Kotlin, a function which can accept a function as parameter or can return a function is called Higher-Order function. Instead of Integer, String or Array as a parameter to function, we will pass anonymous function or lambdas. Frequently, lambdas are passed as parameter in Kotlin functions for the convenience.

How do you pass a context in a constructor in Kotlin?

Define an interface with the same factory function and two objects for the scopes. Define a function that takes the scope and the initializer block. Now you can use the useScope -Function and within the block the right factory function is invoked. Save this answer.

What are the two types of constructors in Kotlin?

A Kotlin class can have following two type of constructors: Primary Constructor. Second Constructors.


2 Answers

You can have a property with a function type just like you would with any other type:

class A(val f: () -> Unit) {

    fun foo() {
        f()
    }

}

From here, you can pass that function to the constructor as a method reference:

fun bar() {
    println("this is bar")
}

val a = A(::bar)
a.foo()             // this is bar

Or as a lambda:

val a = A({ println("this is the lambda") })

And you can even do the usual syntactic sugar for lambdas that are the last parameter of a function (although this is getting a little wild):

val a = A { println("this is the lambda") }
like image 79
zsmb13 Avatar answered Oct 01 '22 12:10

zsmb13


If you have more than one constructor declarations you can use this

...

private var listener : (() -> Unit)? = null

constructor(context: Context, listener: (() -> Unit)?) : this(context){
        this.listener = listener
}

constructor(context: Context) : super(context, attrs = null)

...
like image 39
arsent Avatar answered Oct 01 '22 14:10

arsent