Home > OS >  How to annotate lambda's return value
How to annotate lambda's return value

Time:12-08

I have a function with lambda parameter:

private fun MyFun(
    progress: () -> Float,
) {
    // ...
}

I want to annotate return value of progress lambda with @FloatRange(from = 0.0, to = 1.0), but can't figure out how to do this. All my attempts to solve this causes syntax errors. Where am I wrong?

CodePudding user response:

In kotlin language, lambda to perform a task, not to annotate. You can comment code likes this // FloatRange(from = 0.0, to = 1.0)

example :

// FloatRange(from = 0.0, to = 1.0)

private fun MyFun(

progress: () -> Float,

) {

}

you can read here to better understand lambda in kotlin language

CodePudding user response:

You can define a functional interface to describe your type, and annotate it there:

fun interface ProgressCallback {
    @FloatRange(from = 0.0, to = 1.0) fun progress(): Float
}

private fun myFun(progress: ProgressCallback) {
    // ...
}

fun foo() {
    myFun { 5.0f } // error, doesn't conform to FloatRange
}

FYI, lint is not sophisticated enough to detect a failure to meet the requirement if you pass a function reference instead of a lambda, or if you indirectly call a function that returns a Float:

fun bar() = 5.0f

fun foo() {
    myFun(::bar) // no error
    myFun { bar() } // no error
}

Or if you return anything besides a single literal value:

fun foo() {
    myFun { 1.0f * 2.0f } // no error
}
  • Related