Scala | 特性应用
特性应用
Scala使用称为“App”的特征,该特征用于将对象转换为可行的程序。此转换使用DelayedInit完成,并且对象继承了名为App的特征,将使用此函数。这会将程序代码转换为main中继承的方法。
语法:
trait App extends DelyedInit
让我们看一个例子,以更好地理解该主题,
在此示例中,我们将使用Apptrait创建一个程序,该程序将从命令行获取参数并打印其乘积。
object myObject extends App
{
if (args.length == 1)
{
var product = {args(0).toInt}*1
println("Product is "+ product)
}
else if (args.length == 2)
{
var product = {args(0).toInt}*{args(1).toInt}
println("Product is "+ product)
}
else
{
println("Values not found.")
}
}输出结果
Command-line: 2 4 Product is 8
在这里,带有App的对象将充当主要功能,并将接受参数并根据需要执行操作。