Thursday, August 22, 2013

Simple scala programs

1. Prints true if N corresponds to a leap year, and false otherwise.

  def isLeapYear(year: Int){  
     var isLeapYear:Boolean=false;  
     // divisible by 4  
     isLeapYear = (year % 4 == 0) && (year % 100 != 0);  
     // divisible by 4 and not 100 unless divisible by 400  
     isLeapYear = isLeapYear || (year % 400 == 0);  
     println(isLeapYear);  
  }  

2.Sort your collection using sortby API

 object Hello {  
  case class Person(name: String, age: Int) {    
   //Overridding toString() method for simplicity  
   override def toString() = {  
    "Name :" + name + " age:" + age  
   }  
  }  
  val people: Array[Person] = Array(Person("Amol", 30), Person("Kiran", 32), Person("Raj", 19))  
  def main(args: Array[String]) {  
   var sortedPeople = people.sortBy(_.age);  
   for (p <- sortedPeople) {  
    println(p.toString)  
   }  
  }  
 }  



3. Reading a text file and printing it line by line
import scala.io._
object ReadFile extends Application {
  val s = Source.fromFile("Test.txt")
  s.getLines.foreach( (line) => {
    println(line.trim.toUpperCase)
  })
}