scala – sealed abstract class

sealed abstract class Expr case class Var(name: String) extends Expr

case class Number(num: Double) extends Expr

case class UnOp(operator: String, arg: Expr) extends Expr

case class BinOp(operator: String, left: Expr, right: Expr) extends Expr

 

def describe(e: Expr): String = e match {

case Number(_) => “a number” case Var(_) => “a variable”

}
You will get a compiler warning like the following:
warning: match is not exhaustive! missing combination UnOp missing combination BinOp

def describe(e: Expr): String = e match {

case Number(_) => “a number” case Var(_) => “a variable”

case _ => throw new RuntimeException // Should not happen }
That works, but it is not ideal. You will probably not be very happy that you were forced to add code that will never be executed (or so you think), just to make the compiler shut up.

A more lightweight alternative is to add an @unchecked annotation to the selector expression of the match.
def describe(e: Expr): String = (e: @unchecked) match {

case Number(_) => “a number”

case Var(_) => “a variable” }

 

Scala – Option type

Scala has a standard type named Option for optional values. Such a value can be of two forms. It can be of the form Some(x) where x is the actual value. Or it can be the None object, which represents a missing value.

 

it is possible to store value types in hash maps, and null is not a legal element for a value type. For instance, a HashMap[Int, Int] cannot return null to signify “no element.” By contrast, Scala encourages the use of Option to indicate an optional value. This approach to optional values has several advantages over Java’s. First, it is far more obvious to readers of code that a variable whose type is Option[String] is an optional String than a variable of type String, which may sometimes be null. But most importantly, that programming.

 

object OptionType extends App{

  val m1 = Map("usa"-> "DC","India"->"delhi")
  def show(x: Option[String]) = x match {
    case Some(s) => s
    case None => "?" }
  println(show(m1.get("china")))
  println(show(m1.get("Core Universe")))
  println(show(m1.get("India")))

}

scala – currying

object Fn_Multi_Curry extends App {

  // Multi-argument functions:
  def h(x : Int, y : Int) : Int = x + y

  // A Curried multi-argument function:
  def hC (x : Int) (y : Int) : Int = x + y

  // Wrong: hC 3 4
  // Right: hC (3) (4)

  // Wrong: hC (3)
  // Right: hC (3) _

  // Wrong: hC _ (4)
  // Right: hC (_:Int) (4)

  val plus3 = hC (_:Int) (3)
  val plus_3 = hC (3) _

  println(plus3(10))
  // Prints:
  // 13

  println(plus_3(5))
//8
}

scala – apply method

object  Class_apply extends App {


  // class with apply method:
  class Identity {
    def apply(x : Int) = x
  }
  val myId = new Identity

  // f(x) => f.apply(x)

  // object with apply method:
  object Id {
    def apply(x : Int) = x
  }


  println(Id.apply(3))
  // Prints:
  // 3

  println(myId.apply(4))
  // Prints:
  // 4

  println(Id(5))
  // Prints:
  // 5

  println(myId(6))
  // Prints:
  // 6

  // anonymous class with apply method:
  val myOtherId = new {
    def apply(x : Int) = x
  }

  // case blocks also act as functions:
  val myCaseID : Int => Int = {
    case x => x
  }


  println(myOtherId(7))
  // Prints:
  // 7

  println(myCaseID(8))
  // Prints:
  // 8

}

scala – symbol,xml,Range,Tuples,Map,Set,unit(),null

object ScalaSnippets  extends App{

  //Find the last element of a list.
  println(List(1, 1, 2, 3, 5, 8).last)

  //Find the last but one element of a list.
  //println(List(1, 1, 2, 3, 5, 8).penultimate)


  // Floating point:
  val aDouble = 4.0
  // Charaters:
  val aCharacter = 'c'

  // Strings:
  val aString = "Google"

  // Symbols:
  val aSymbol = 'foo
  println("asymbol:"+aSymbol)

  // XML:
  val anXMLElement = <a href="http://www.google.com/">{aString}</a>
println("xml:"+anXMLElement)


  val aRange = 1 to 5
  println(aRange)

  // Tuples:
  val aPair = (aString,aDouble)
  println(aPair)

  // Maps:
  val aMap = Map(3 -> "foo", 4 -> "bar")

println(aMap)

  // Sets: (can sets be declared with duplicate elements??)
  val aSet = Set(8,9,10,10)

  println(aSet) // gives only 8,9,10
  // Arrays:

  val arr=Array(1,2,3)
  println(arr)

  // Unit:
  val unit=()
  println(unit)

  // Null:
  val nullval=null
  println(nullval)


}

 

 

scala – List – scala.StringBuilder

There are also variants of the mkString methods called addString which append the constructed string to a StringBuilder object

The mkString and addString methods are inherited from List’s supertrait Traversable, so they are applicable to all other collections, as well.

object List_StringBuilder extends App{

val lst=List("america","india")
  val buf = new StringBuilder
  println(lst addString (buf, "(", ";", ")"))
  //stringbuilder object

}

(america;india)

scala – List- mkstring

The operation xs mkString (pre, sep, post) involves four operands: the list xstobedisplayed,aprefixstringpretobedisplayedinfrontofallelements, a separator string sep to be displayed between successive elements, and a postfix string post to be displayed at the end. The result of the operation is the string:
pre + xs(0) + sep + …+ sep + xs(xs.length – 1) + post

 

The mkString method has two overloaded variants that let you drop some or all of its arguments. The first variant only takes a separator string:
xs mkString sep equals xs mkString (“”, sep, “”)
The second variant lets you omit all arguments:
xs.mkString equals xs mkString “”

 

object List_mkstring extends App{

  val lst=List(1,2,3)
  println(lst.mkString("##","*","&&"))

  println(lst mkString "#")

  println(lst mkString)
}

##1*2*3&&
1#2#3
123