简体   繁体   中英

Kotlin: higher order function with recursion

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?

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM