Given the type-alias type Cal = java.util.Calendar
how can the static
getInstance
method be accessed? I tried the following in Scala REPL:
scala> type Cal = java.util.Calendar
defined type alias Cal
scala> Cal.getInstance
<console>:8: error: not found: value Cal
Cal.getInstance
^
scala> val Cal = java.util.Calendar
<console>:7: error: object Calendar is not a value
val Cal = java.util.Calendar
^
Is import java.util.{Calendar => Cal}
followed by import Cal._
really my best bet?
To call a static method from another class, you use the name of the class followed by the method name, like this: ClassName.
A static method can be called directly from the class, without having to create an instance of the class. A static method can only access static variables; it cannot access instance variables. Since the static method refers to the class, the syntax to call or refer to a static method is: class name. method name.
In Scala, we use class keyword to define instance members and object keyword to define static members. Scala does not have static keyword, but still we can define them by using object keyword. The main design decision about this is that the clear separation between instance and static members.
In Scala there are no static methods: all methods are defined over an object, be it an instance of a class or a singleton, as the one you defined in your question.
You can't.
Yes, import java.util.{Calendar => Cal}
is really your best bet.
Conceptually, Scala object
members are similar to static members of Java classes. This might suggest the following would work, but it doesn't since there are actually no singleton objects available for Java classes.
scala> val Cal = java.util.Calendar
<console>:13: error: object Calendar is not a value
val Cal = java.util.Calendar
^
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With