Reputation: 83
I have to create a higher order function which returns a lambda to learn functional programming with Kotlin.
This is the class
class Product (val productName : String, val price : Double, val rating : Int) {
override fun toString () = "$productName, $price, $rating"
}
this is my function
fun productFactory (productName: String , rating : Int) : (Double) -> Product {
val x : (Double) -> Product = productFactory(productName, rating)
return x
}
this is how I call the function
val cheese = productFactory("Gouda", 5)
val product = cheese(4.99)
Although it seems to work with the needed constructors, it causes a StackOverflowError and I don't know, where the problem is. Can anybody help me?
Upvotes: 2
Views: 274
Reputation: 93629
Your function productFactory
is recursively calling itself with no way to exit the recursion, so it will always cause a stack overflow.
The function it returns should certainly not be itself because the behavior is different.
You can define the returned function as a lambda:
fun productFactory (productName: String , rating : Int) : (Double) -> Product {
return { price -> Product(productName, price, rating) }
}
or use function syntax and return the function using the ::
operator:
fun productFactory (productName: String , rating : Int) : (Double) -> Product {
fun produce(price: Double) = Product(productName, price, rating)
return ::produce
}
Upvotes: 1