Separating lambda from constructor


#1

I am trying to separate the declared lambda from constructor like this

class ClassA(var sample:(msg:String)->Unit) {

    lateinit var sampleLambda2:(msg:String)->Unit
    inner class ClassB{
        init {
           sample("okay")
            sampleLambda2("msg")
        }
    }
}

The sample() works when I called it on my Main

val c = ClassA(){
    print(it)
}

but the Lambda variable doesn’t. why is that? Im really confuse. How can I achieve the same call on main but with separation of lambda from constructor? How do you call it on inner class?


#2

You defined your lateinit variable sampleLambda2 but never assigned it to anything. What do you expect it to do?


#3

I am not exactly sure what you are asking for. I will show 2 possible answers

class ClassA(var sample:(msg:String)->Unit) {

    var sampleLambda2 = sample
    inner class ClassB{
        init {
           sample("okay")
            sampleLambda2("msg")
        }
    }
}

Or

class ClassA( sample:(msg:String)->Unit) {

    var sampleLambda2 = sample
    inner class ClassB{
        init {
            sampleLambda2("msg")
        }
    }
}

#4

My Goal is to separate the lambda from constructor to a separate function where I could call on inner class same as the example about. I can call the lambda from the ClassA constructor and then on my main pass a function.


#5

Is it posible to separate the lambda from constructor and make it its own thing? I wanted to separate it from constructor yet at the same time be able to call it from my inner class and then on my main pass a function?


#6

I don’t really understand what do you mean by separating from constructor. You want to pass it as a parameter later? In kotlin functions work exactly like any other objects, you can assign field sampleLambda2 after object creation, but you do need to assign it. In your example it is not assigned and will throw a lateinit exception.


#7

What I want is to not declare the lambda from constructor. But sort of like a function with in ClassA and can be called by the inner class like this

sample("Hello")

and then on main I could call it like

val c = ClassA()
c.sample{
print(it)
}

#8
class ClassA() {
    private var sample: ((String) -> Unit)? = null
    fun sample(func: (String) -> Unit){
        this.sample = func
    }
}

#9

I see, so it seems that kotlin itself doesn’t like this approach. I get this error property getter or setter expected


#10

I added extra round bracket. Fixed the example.


#11

Awesome it works. Thank you. This is so much better than putting a lot of lambda on constructors