简体   繁体   English

为什么Scala从对象的main方法而不是类的static main方法开始?

[英]Why does Scala starts from an object's main method instead of a class's static main method?

In Java, a program starts from a class's static main method. 在Java中,程序从类的静态main方法开始。 But in Scala, it starts from a object's main method. 但是在Scala中,它是从对象的main方法开始的。

Does anyone know the rationality of designing like this? 有人知道这样设计的合理性吗?

Scala also provide a trait called App , which can replace main method if an object extends this trait. Scala还提供了一个名为App的特征,如果对象扩展了该特征,它可以替代main方法。 Does anyone have ideas about which one ( App or main ) is the preferred way? 是否有人对首选方式( Appmain )有所了解?

Thanks! 谢谢!

Scala has singleton objects instead of java static members. Scala具有单例对象,而不是Java静态成员。 So main method of object is analogue of java static main method. 因此对象的主要方法类似于java静态主要方法。

I always extend App in my main class, and know of no reason why anyone would want to write an explicit main method -- except possibly to be compatible with some other code that was overly fussy about such things. 我总是在我的主类中扩展App ,并且不知道为什么有人会想编写一个显式的main方法-除了可能与某些过于繁琐的代码兼容之外。 Whenever I see an explicit main method in Scala, I wonder whether the code is very old (predating the App trait) or the author was new to Scala. 每当我在Scala中看到显式的main方法时,我都会想知道代码是不是很旧(比App特质早)或者作者是Scala的新手。

But this question appears to largely be about why the designers of Scala omitted static methods. 但是,这个问题似乎很大程度上与Scala的设计者为什么省略静态方法有关。 You may find this question about how static members are not object-oriented helpful. 您可能会发现有关静态成员不是面向对象的帮助的问题。

Scala doesn't have static methods. Scala没有静态方法。 If Scala required starting programs from a static main method, then you could never run a Scala program, because you couldn't write a static main method. 如果Scala需要从静态主方法启动程序,那么您将永远无法运行Scala程序,因为您无法编写静态主方法。

Using static is like using global functions. 使用静态就像使用全局函数。 Scala is pure object oriented language and has no statics. Scala是纯面向对象的语言,没有静态变量。 But in fact Scala compiler generates static main for JVM. 但是实际上,Scala编译器会为JVM生成静态主程序。 It is recommended to use 'App' trait for short study programs. 对于短期学习计划,建议使用“ App”特征。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM