Posts

Showing posts with the label scala

Strings In Scala

Image
    At first glance, a Scala String appears to be just a Java String. Indeed, a Scala String is a Java String, so you can use all the normal java Strings methods. Calling getName method on String class results a java.lang.String. Calling getName method of String class in REPL  You can create a String variable, albeit in the Scala way.  val s = "Hello, World" // Immutable String s represents "Hello, World" You can get the length of a String  s.length // 12 You can concatenate Strings val s = "Hello" + "World" Magic Of Implicit Conversions:      The above all are familiar operations. In Scala, Strings instances also have access to all the methods of the StringOps class. So you can do many other things with them , for example, treating String instance as a sequence of characters. As a result, you can iterate over every character in the String using foreach method. scala > "Hello".foreach(println) ...

The "Hello, World" Program In Scala

Image
    While learning any programming language, we were used to execute a program that prints "Hello, World" as the first program . Here is the standard Hello World program using Scala. object HelloWorld {     def main(args : Array[String]) {       println("Hello, world!")     } } If you are coming from java, this program can be compared with the below java "Hello World" program. public class HelloWorld {      public static void main(String[] args) {           System.out.println("Hello, World!");      } } Both Java, & scala requires main method with String arguments, in order to execute the program. The method definition is slightly different in Scala, when compared to Java, as you can see in the above programs. In any application we will have only one public class with a main method. This is conceptually similar to singleton pattern. So in Scala , you can define singl...