One of Scala's strengths is that it can be very simple to interact with existing Java code, and all classes in Java.lang have been automatically imported, while others need to explicitly declare imports. Let's take a look at the demo code. We want to format the date, for example the format of the country of use. The Java Class Library defines a series of useful classes, such as date and DateFormat. Since Scala has a good interaction with Java, we don't need to implement the equivalent code in the Scala class library, but simply import the relevant Java classes: Import Java.util. {Date, Locale} Import Java.text.DateFormat Import Java.text.dateformat._ object Frenchdate {def main (args:array[string]) {val now = NE W Date val df = getdateinstance (LONG, locale.france) println (DF Format Now)}} Scala's import statement looks very similar to Java's, but it's more powerful. You can use curly braces to import multiple classes in the same package, just like the first line in the code above. Another difference is that when you import all the classes or symbols in a package, you should use an underscore (_) instead of an asterisk (*). This is because the asterisk is a valid identifier in Scala (for example, as a method name). This example we will encounter later. The import statement in the third row imports all the members in the DataFormat class, which makes the static method getdateinstance and the static variable long can be directly referenced. In the main function, we first set up a Java date instance. This instance will contain the current time by default. Next we define the date format using the static function getdateinstance just imported. Finally, we will print out the date formatted with Datafotmat. The last line of code shows an interesting syntax for Scala: a function with only one parameter can be represented by an expression such as the following: DF Format Now In fact, this is the simple wording of this lengthy expression. Df.format (now) This looks like a syntax detail, but it causes an important consequence that we will explain in the next section. In addition, we should also note that Scala can directly inherit or implement interfaces and classes in Java. |
For more highlights, please follow: http://bbs.superwu.cn
Focus on Superman Academy QR Code: 650) this.width=650; "Src=" http://s3.51cto.com/wyfs02/M00/6D/63/wKiom1Vi0LvxLnlCAADAdZasjL0908.jpg " Title= "Superman Academy. jpg" alt= "wkiom1vi0lvxlnlcaadadzasjl0908.jpg"/>
Scala interacts with Java