Function 如何创建此高级Kotlin函数?
我希望创建如下自定义函数:Function 如何创建此高级Kotlin函数?,function,kotlin,Function,Kotlin,我希望创建如下自定义函数: customFunction(arg1, arg2, arg3, etc.){ doSomethingIfConditionIsAccomplished() } private fun <T: Comparable<T>> customFunction(vararg input: T){ val condition = (1 until input.size).none { input[it] < input[it-1
customFunction(arg1, arg2, arg3, etc.){
doSomethingIfConditionIsAccomplished()
}
private fun <T: Comparable<T>> customFunction(vararg input: T){
val condition = (1 until input.size).none { input[it] < input[it-1] }
if(condition) {
println("calling doSomethingIfConditionIsAccomplished()")
} else {
println("not calling doSomethingIfConditionIsAccomplished()")
}
}
fun main() {
customFunction(1,2,3) // -> calling doSomethingIfConditionIsAccomplished()
customFunction(2,1,3) // -> not calling doSomethingIfConditionIsAccomplished()
}
,其中函数接受vararg
作为参数,以便您可以添加任意数量的参数,并且只有在验证函数中的特定条件时,方可运行括号内的函数doSomethingif ConditionisCompleted()
,如:
如果(arg1>arg2>arg3)->允许dosomethingif conditionisaccompleted()
函数运行,否则什么也不会发生
该函数应类似于:
private fun <T: Any> customFunction(vararg input: T?){
-condition-
}
private fun自定义函数(vararg输入:T?){
-状况-
}
由于vararg只是函数中的一个数组,因此可以执行以下操作:
customFunction(arg1, arg2, arg3, etc.){
doSomethingIfConditionIsAccomplished()
}
private fun <T: Comparable<T>> customFunction(vararg input: T){
val condition = (1 until input.size).none { input[it] < input[it-1] }
if(condition) {
println("calling doSomethingIfConditionIsAccomplished()")
} else {
println("not calling doSomethingIfConditionIsAccomplished()")
}
}
fun main() {
customFunction(1,2,3) // -> calling doSomethingIfConditionIsAccomplished()
customFunction(2,1,3) // -> not calling doSomethingIfConditionIsAccomplished()
}
private fun自定义函数(vararg输入:T){
val条件=(直到input.size为止为1)。无{input[it]调用doSomethingif条件已完成()
customFunction(2,1,3)/->不调用doSomethingif ConditionisAccompled()
}
但这样,条件是硬编码的,T
必须是可比的
。编写这样的方法没有任何意义,除非您想要实现策略
模式,但这有点不同。如果(arg1>arg2>arg3)
更具体一些,这对于T:Any