Reputation: 459
Suppose I have
fun getRealGrade(x: Double) = x
fun getGradeWithPenalty(x: Double) = x - 1
fun getScoringFunction(isCheater: Boolean): (Double) -> Double {
if (isCheater) {
return ::getGradeWithPenalty
}
return ::getRealGrade
}
What is the use of (Double) -> Double
in getScoringfunction
?
If I dont undestand the syntax correct me isCheater
val is boolean here, and function returns double but what does this (Double)
do?
What I get is:
fun sayHello() {
println("Hello")
}
In this example
sayHello
has a type of () -> Unit
Upvotes: 0
Views: 51
Reputation: 3476
The function doesn't return a (Double)
, it returns a (Double) -> Double
, i.e. it returns a function. The function that it returns takes a double and returns a double.
You would use it like this
fun main() {
val scoreFunction: (Double) -> Double = getScoringFunction(true); // returns the cheater scoring function
val score = scoreFunction(10) // score = 9, they were graded with penalty
}
In your second example, the return type is Unit
. In Kotlin, a function that returns no value is said to return Unit
, a singleton object. () -> Unit
is a function that takes no parameters and returns no value.
Upvotes: 2