为什么不大写类名会在此处导致编译器错误? [英] Why does not capitalizing the class name cause a compiler error here?
问题描述
此Groovy脚本运行正常:
This Groovy script runs fine:
println 0;
class MyClass
{
public MyClass(int j) {};
public MyClass method() {return this};
}
此操作失败,并出现编译错误(意外令牌:第5行,第4列,公开:")
This one fails with a compilation error ("unexpected token: public at line: 5, column: 4")
println 0;
class myClass
{
public myClass(int j) {};
public myClass method() {return this};
}
唯一的区别是类名的大写.我知道约定是将类名大写,但我认为这只是一个约定.究竟是什么导致编译错误?
The only difference is the capitalization of the class name. I know the convention is for class names to be capitalized, but I thought it was just a convention. What exactly causes the compile error?
推荐答案
According to a Groovy mailing list thread from 2008, where a similar question was posed, Paul King explained:
是的,语法目前仅在声明中查找大写类型(原始类型除外).
Yes, the grammar currently looks for uppercase types only in declarations (apart from the primitive types).
在最近的版本中,关于小写类名的未解决的Groovy JIRA票证
In a more recent, unresolved Groovy JIRA ticket regarding lowercase class names, blackdrag comments that:
问题在于,在Groovy(与Java不同)中,变量名,方法名和类名可以共享上下文,从而使其变得模棱两可.
The problem is that in Groovy (unlike Java) variable names, method names and class names can share a context, making it ambiguous.
除非对标记符进行更深入的研究,由于Groovy的语法灵活性,所以我将这归结为Java和Groovy之间的另一个次要矛盾之处. Groovy并没有完全实现一种在这种情况下辨别令牌是类型还是方法名称的方法,而是采取了捷径,并且仅假设令牌与基本类型匹配或以大写字母开头,则可以假设它可以是类型名称,例如常规的Java类型.
Barring a deeper exploration of the tokenizer, I'll just chalk this up as another minor inconsistency between Java and Groovy due to Groovy's syntax flexibility. And instead of thoroughly implementing a way to tell if a token is a type or method name in this context, Groovy takes a short cut and only assumes it can be a type name if the token matches a primitive or begins with a capital letter, as conventional Java types would.
这篇关于为什么不大写类名会在此处导致编译器错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!