在Kotlin中,函数是一等公民,这意味着函数可以像其他数据类型一样被传递和存储。将函数作为构造函数参数传递是一种强大的技术,它允许在对象创建时注入行为,从而实现更灵活的代码结构。
Kotlin中有几种表示函数类型的方式:
(参数类型) -> 返回类型
class Processor(private val processFunction: (String) -> String) {
fun process(input: String): String {
return processFunction(input)
}
}
fun main() {
// 传入lambda作为构造函数参数
val upperCaseProcessor = Processor { it.uppercase() }
println(upperCaseProcessor.process("hello")) // 输出: HELLO
// 传入函数引用
val lowerCaseProcessor = Processor(String::lowercase)
println(lowerCaseProcessor.process("WORLD")) // 输出: world
}
class DataTransformer(
private val transform: (Int) -> String,
private val validate: (Int) -> Boolean = { it > 0 }
) {
fun transformData(input: Int): String? {
return if (validate(input)) transform(input) else null
}
}
fun main() {
val hexTransformer = DataTransformer(
transform = { it.toString(16) },
validate = { it in 1..1000 }
)
println(hexTransformer.transformData(255)) // 输出: ff
println(hexTransformer.transformData(0)) // 输出: null
}
fun interface StringFilter {
fun filter(input: String): Boolean
}
class TextProcessor(filter: StringFilter) {
private val currentFilter = filter
fun processText(text: String): String {
return if (currentFilter.filter(text)) text else ""
}
}
fun main() {
val processor = TextProcessor { it.length > 5 }
println(processor.processText("Kotlin")) // 输出: Kotlin
println(processor.processText("Hi")) // 输出: (空字符串)
}
问题:如何处理可能为null的函数参数?
解决方案:明确指定可空类型或提供默认实现
class Service(
private val callback: ((String) -> Unit)? = null
) {
fun doWork() {
// 使用安全调用操作符
callback?.invoke("Work done")
}
}
问题:频繁创建包含函数参数的类实例是否影响性能?
解决方案:
问题:调试时难以追踪传入的函数实现
解决方案:
class Calculator(
private val operation: (Double, Double) -> Double
) {
fun calculate(a: Double, b: Double): Double {
println("Performing operation with $a and $b")
return operation(a, b)
}
}
fun main() {
val adder = Calculator { x, y -> x + y }
println(adder.calculate(2.5, 3.5)) // 输出: 6.0
}
class QueryBuilder(private val condition: (String) -> Boolean) {
infix fun and(other: QueryBuilder): QueryBuilder {
return QueryBuilder { condition(it) && other.condition(it) }
}
fun test(input: String): Boolean = condition(input)
}
fun main() {
val startsWithA = QueryBuilder { it.startsWith("A") }
val endsWithZ = QueryBuilder { it.endsWith("z") }
val combined = startsWithA and endsWithZ
println(combined.test("A quick brown fox")) // false
println(combined.test("Alphabetz")) // true
}
class Transformer<T, R>(
private val transformFunction: (T) -> R
) {
fun transform(input: T): R = transformFunction(input)
}
fun main() {
val intToString = Transformer<Int, String> { "Number: $it" }
println(intToString.transform(42)) // 输出: Number: 42
val stringToLength = Transformer<String, Int>(String::length)
println(stringToLength.transform("Kotlin")) // 输出: 6
}
通过将函数作为构造函数参数传递,Kotlin提供了极大的灵活性和表现力,使代码更加模块化和可维护。
没有搜到相关的文章