Scala 特质App
App是一个特质,利用这个特质可以迅速将对象变为可行的程序,这是由应用DelayedInit函数来进行的,继承该特质的对象App使用这个函数来执行整个程序的主体,作为继承的main方法的一个部分。
注。
trait App extends DelayedInit
- 这里的线性超级类型是。
DelayedInit, AnyRef, Any
- value成员是:
val executionStart: Long
def main(args: Array[String]): Unit
现在,让我们看看一些例子。
* 示例 :
// Scala program of a trait
// App
// Applying the trait App
object GfG extends App
{
// Displays output
println("GeeksforGeeks")
}
输出:
GeeksforGeeks
在这里,对象GfG继承了App的主方法并打印输出,因此我们不需要手动创建主方法。
- 示例:
// Scala program of trait
// App
object GfG extends App
{
// conditions stated
if (args.length == 1)
{
// Displays this as output if
// the command line arguments
// are equal to one
println("Student: ${args(0)}")
}
else
{
// Displays this if no arguments
// are given in the command line
println("There are no students.")
}
}
输出:
There are no students.
注意:在这里,args被用来表示命令行参数,它将像一个数组一样返回即时的命令行参数。
由于没有提供命令行参数,这里得到的输出是上面else部分中的字符串。如果我们像下面那样提供命令行参数,那么输出将是。
// command line argument
$ scala GfG Nidhi
// Output
Student: Nidhi
这里,只给了一个参数,所以只返回这个参数。
极客教程