Kotlin:带递归的高阶函数
Kotlin: higher order function with recursion
我必须创建一个高阶函数,其中 returns 一个 lambda 来学习使用 Kotlin 进行函数式编程。
这是class
class Product (val productName : String, val price : Double, val rating : Int) {
override fun toString () = "$productName, $price, $rating"
}
这是我的功能
fun productFactory (productName: String , rating : Int) : (Double) -> Product {
val x : (Double) -> Product = productFactory(productName, rating)
return x
}
这就是我调用函数的方式
val cheese = productFactory("Gouda", 5)
val product = cheese(4.99)
虽然它似乎与所需的构造函数一起工作,但它会导致 WhosebugError,我不知道问题出在哪里。有人可以帮助我吗?
你的函数productFactory
正在递归调用自身,没有办法退出递归,所以它总是会导致堆栈溢出。
它return的函数当然不应该是它自己,因为行为不同。
您可以将 returned 函数定义为 lambda:
fun productFactory (productName: String , rating : Int) : (Double) -> Product {
return { price -> Product(productName, price, rating) }
}
或使用函数语法和 return 使用 ::
运算符的函数:
fun productFactory (productName: String , rating : Int) : (Double) -> Product {
fun produce(price: Double) = Product(productName, price, rating)
return ::produce
}
我必须创建一个高阶函数,其中 returns 一个 lambda 来学习使用 Kotlin 进行函数式编程。
这是class
class Product (val productName : String, val price : Double, val rating : Int) {
override fun toString () = "$productName, $price, $rating"
}
这是我的功能
fun productFactory (productName: String , rating : Int) : (Double) -> Product {
val x : (Double) -> Product = productFactory(productName, rating)
return x
}
这就是我调用函数的方式
val cheese = productFactory("Gouda", 5)
val product = cheese(4.99)
虽然它似乎与所需的构造函数一起工作,但它会导致 WhosebugError,我不知道问题出在哪里。有人可以帮助我吗?
你的函数productFactory
正在递归调用自身,没有办法退出递归,所以它总是会导致堆栈溢出。
它return的函数当然不应该是它自己,因为行为不同。
您可以将 returned 函数定义为 lambda:
fun productFactory (productName: String , rating : Int) : (Double) -> Product {
return { price -> Product(productName, price, rating) }
}
或使用函数语法和 return 使用 ::
运算符的函数:
fun productFactory (productName: String , rating : Int) : (Double) -> Product {
fun produce(price: Double) = Product(productName, price, rating)
return ::produce
}