How to create a class that takes function as a constructor argument. Then, use this function at some later point in the class.
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 ).
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.
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.
A Kotlin class can have following two type of constructors: Primary Constructor. Second Constructors.
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") }
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)
...
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