Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access a Java static method from Scala given a type alias for that class it resides in

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?

like image 979
Tim Friske Avatar asked Oct 05 '11 21:10

Tim Friske


People also ask

How do you reference a static method from another class?

To call a static method from another class, you use the name of the class followed by the method name, like this: ClassName.

How do you access a static method?

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.

How do you use static in Scala?

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.

Are there static methods in Scala?

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.


1 Answers

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
                           ^
like image 71
missingfaktor Avatar answered Oct 10 '22 03:10

missingfaktor