How do I provide an implementation for a function type?

60 views Asked by At

Concerning function types in Kotlin The following gives exception kotlin.UninitializedPropertyAccessException: lateinit property foo has not been initialized

class SomeClass (){
    lateinit var foo: (String) -> Int
}  

val result : Int = c.foo("hello")
println("result $result")  

The following 2 do not even compile

class SomeClass (){
    lateinit var foo: (String) -> Int = 1
}

class SomeClass (){
    var foo: (String) -> Int = 1
}

How do I provide an implementation for foo?

2

There are 2 answers

4
Stanislav Bondar On

You can declare foo function as val in this way

val foo: (String) -> Int = { someIntResult } 

and use it like foo.invoke("") or if you need to use lateinit var you should initialize it later in class

1
Demigod On

I'm really not sure what you're trying to achieve, but it should as simple as @StanislavBondar answer.

fun main() {
    println("Hello, world!!!")

    val test = Test()
    test.foo = { it.length }
    println(test.foo("ass"))
}

class Test {
    lateinit var foo: (String) -> Int
}

You can try it here If it will still throw an UninitializedPropertyAccessException - most likely you're trying to access not initialized property (access before initialization, or access on another instance, etc.)