Menu
CoddyTech

组合与委托

Coddy 面向 C++ 开发者的 Kotlin 课程的第 38 课,共 48 课。

C++ 组合可以持有值、引用或智能指针,每种方式都有其所有权策略。Kotlin 存储协作对象引用,并可以暴露显式的接口契约。使用调用者选择的协作对象,而不是默默地构建默认对象。使用 by 进行接口委托可以转发行为,但在学习时,手动委托能使选定的调用路径更加清晰。

C++

#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <algorithm>
#include <numeric>
#include <optional>
#include <functional>
#include <sstream>
#include <variant>
#include <memory>
#include <cctype>
#include <stdexcept>

struct Fee {int amount()const{return 4;}};struct Checkout {const Fee& fee;int total(int n)const{return n+fee.amount();}};
int main() {
std::cout << std::boolalpha;
Fee fee;Checkout checkout{fee};std::cout << checkout.total(6) << "\n";
}

Kotlin

fun interface Title{fun get():String};class Page(private val title:Title){fun text():String="<${title.get()}>"}
fun main(){
println(Page(Title { "hello" }).text())
}

迁移陷阱

共享的对象引用并不是其协作对象的 C++ 值拷贝。

在单独的练习中应用此概念。示例使用的是不同的操作或模型;请保留要求的任务 API,并让锁定的入口点负责输入和输出。

challenge icon

挑战

简单

输入是非负单价,然后是单位数。实现带有 open cost(units:Int) 的 open Rate(cents:Int),以及委托给传入 rate 的 UsageBill(rate:Rate).total(units:Int)。返回总费用。

实现可编辑的文件,并返回 Exercise.solve(input: List<String>) 的结果。不要在可编辑的方法内部进行打印。可见且锁定的 Main.kt 会读取所有输入行,并打印你返回的文本,末尾带有换行符。Text.kt 提供解析和格式化辅助函数。除非另有说明,所有算术结果均符合 Int 范围。

可编辑的文件:Rate.kt、UsageBill.kt、Exercise.kt、Text.kt。只有 Main.kt 包含 main;它是锁定的,并且是最后一个文件。所有文件都在同一个包中一起编译。

锁定的驱动程序会使用新的对象和不同的协作对象独立调用所需的公共 API。请实现这些行为;仅复现测试用例的输出是不够的。

亲手试试

fun main() {
    val input = generateSequence { readlnOrNull() }.toList()
    check(Rate(6).cost(3)==18);val special=object:Rate(1){override fun cost(units:Int):Int=units+17};check(UsageBill(special).total(5)==22)
    println(Exercise.solve(input))
}
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

面向 C++ 开发者的 Kotlin中的所有课

自己练习: Kotlin 在线编辑器