[ACCEPTED]-Scala: public static final in a class-scala
object Foo{
val MY_STRINGS=Array("A","B","C")
}
class Foo{
import Foo.MY_STRINGS
}
The val
definition in the companion object 8 creates your public static final
variable, and the import
declaration 7 gives it a nice easy alias in the code you're 6 using to write the class.
Note that the public static final
variable 5 in Scala still will compile to look like 4 a static method call if you call this code 3 from Java.
Edit: I'm slightly wrong because of 2 a bug in Scala 2.7, which I demonstrate 1 in detail in another answer.
The following Scala code:
class Foo{
import Bar.MY_STRINGS
}
object Bar{
val MY_STRINGS=Array("A","B","C")
}
Generates the following 9 Java classes:
public final class Bar extends java.lang.Object{
public static final java.lang.String[] MY_STRINGS();
public static final int $tag() throws java.rmi.RemoteException;
}
public final class Bar$ extends java.lang.Object implements scala.ScalaObject{
public static final Bar$ MODULE$;
public static {};
public Bar$();
public java.lang.String[] MY_STRINGS();
public int $tag() throws java.rmi.RemoteException;
}
public class Foo extends java.lang.Object implements scala.ScalaObject{
public Foo();
public int $tag() throws java.rmi.RemoteException;
}
The following Scala code:
class Foo{
import Foo.MY_STRINGS
}
object Foo{
val MY_STRINGS=Array("A","B","C")
}
Generates 8 the following Java classes:
public class Foo extends java.lang.Object implements scala.ScalaObject{
public Foo();
public int $tag() throws java.rmi.RemoteException;
}
public final class Foo$ extends java.lang.Object implements scala.ScalaObject{
public static final Foo$ MODULE$;
public static {};
public Foo$();
public java.lang.String[] MY_STRINGS();
public int $tag() throws java.rmi.RemoteException;
}
The fact that 7 static members aren't defined on the class 6 when the object has the same name as the 5 class is Scala Bug #1735 and it's fixed in Scala 2.8 snapshots.
So 4 it looks like TwiP isn't going to work at 3 all unless you either upgrade Scala, or 2 find a way to get TwiP to work with non-Static 1 parameter generation methods.
You just have to define the variable as 4 "val" in a companion object.
object Foo{
val MyStrings = Array("A","B","C")
}
NOTE: final 3 static variables in scala doesn't follow 2 the same convention as in Java. Take a look 1 at: http://docs.scala-lang.org/style/naming-conventions.html
If you use a var then you can create your 6 own getter and setter, and if the value 5 is already set, don't change it.
That may 4 not be the best approach, but it would be 3 helpful if you could explain why you want 2 to use public static final
on a variable, as a better solution 1 might be more obvious then.
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.