Showing posts with label b4235| :::. Show all posts
Showing posts with label b4235| :::. Show all posts

All Operators are Methods : Example

In Scala, all operators are method names.
[raj@Rajkumars-MacBook-Pro ~]$scala -deprecation -feature
Welcome to Scala version 2.10.6 (Java HotSpot(TM) 64-Bit Server VM, Java 1.7.0_45).
Type in expressions to have them evaluated.
Type :help for more information.
//#PS:70
//psn > a30 > a15
scala> /*********************************************
     | Example 1 :  Infix Notation
     | **********************************************/
     | 
     | //Here '+' operator is a Method name
     | val sum = 1.+(2)
<console>:6: warning: This lexical syntax is deprecated.  From scala 2.11, a dot will only be considered part of a number if it is immediately followed by a digit.
       val sum = 1.+(2)
                 ^
<console>:12: warning: This lexical syntax is deprecated.  From scala 2.11, a dot will only be considered part of a number if it is immediately followed by a digit.
       val sum = 1.+(2)
                 ^
sum: Double = 3.0

scala> 

scala> //Here we are using infix Notation    

scala> //where '.', '(' and ')' has been omitted

scala> val sum = 1 + 2 
sum: Int = 3

scala>                 
     | 
     | /*********************************************
     | Example 2 :  Postfix Notation
     | **********************************************/
     | val myvar = 10.toString()
myvar: String = 10

scala> 

scala> // '.', '(' & ')' can be omitted for methods with

scala> // no arguments

scala> val myvar = 10 toString 
<console>:7: warning: postfix operator toString should be enabled
by making the implicit value scala.language.postfixOps visible.
This can be achieved by adding the import clause 'import scala.language.postfixOps'
or by setting the compiler option -language:postfixOps.
See the Scala docs for value scala.language.postfixOps for a discussion
why the feature should be explicitly enabled.
       val myvar = 10 toString 
                      ^
myvar: String = 10
Note : Any method that ends with ':' always binds to the right

Merging Lists

An example to merge 2 Lists
scala> // o990 -> a15

scala> val list1 = List('a','b', 'c')
list1: List[Char] = List(a, b, c)

scala> val list2 = List('d', 'e', 'f')
list2: List[Char] = List(d, e, f)

scala> // Using :::

scala> val res1 = list1 ::: list2
res1: List[Char] = List(a, b, c, d, e, f)

scala> // Using ++

scala> val res2 = list1 ++ list2
res2: List[Char] = List(a, b, c, d, e, f)

scala> // Using concat()

scala> val res3 = List.concat(list1, list2)
res3: List[Char] = List(a, b, c, d, e, f)