Scala 模块化编程与对象相等性深度解析
1. Scala 模块化编程
Scala 提供了强大的模块化编程能力,允许在运行时动态链接模块,还能通过 Scala 代码进行配置,同时在跟踪模块实例时需要注意一些细节。
1.1 运行时链接
Scala 模块可以在运行时进行链接,根据运行时的计算结果决定哪些模块相互链接。以下是一个示例代码,展示了如何在运行时选择数据库并打印其中所有苹果食谱:
object GotApples {
def main(args: Array[String]) = {
val db: Database =
if(args(0) == "student")
StudentDatabase
else
SimpleDatabase
object browser extends Browser {
val database = db
}
val apple = SimpleDatabase.foodNamed("Apple").get
for(recipe <- browser.recipesUsing(apple))
println(recipe)
}
}
运行示例:
$ scala GotApples simple
fruit salad
$ scala GotApples student
$
从上述代码和运行结果可以看出,根据传入的参数不