Thursday, 28 January 2016

Scala Singleton And Companion Objects

Scala classes cannot have static variables or methods. Instead a Scala class can have what is called a singleton object, or sometime a companion object.

A singleton object is declared using the object keyword. Here is an example:



object MainObject {
    def sayHello() {
        println("Hello Krishna Kumar Chourasiya!");
    }
}
 
 
This example defines a singleton object called MainObject. You can call the method sayHello() like this: 

MainObject.sayHello();

Notice, how you write the full name of the object before the method name. No object is instantiated. It is like calling a static method in Java, except you are calling the method on a singleton object instead.

Companion Objects

 When a singleton object is named the same as a class, it is called a companion object. A companion object must be defined inside the same source file as the class. Here is an example:

class MainClass {
    def sayHello() {
        println("Hello! Krishna Kumar Chourasiya");
    }
}

object MainClass {
    def sayHi() {
        println("Hi! Krishna Kumar Chourasiya");
    }
}

In this class you can both instantiate Mainlass and call sayHello() or call the sayHi() method on the companion object directly, like this:

var aMainObj : MainClass = new MainClass();
aMainObj.sayHello();    // print - Hello! Krishna Kumar Chourasiya

MainClass.sayHi();    // print - Hi! Krishna Kumar Chourasiya



 3 Cheers !!!







Example of the Typeclass Pattern in Scala

What is a type class and why do I need it?

Type classes are useful to solve several fundamental challenges in programming languages. In particular, type classes support retroactive extension: the ability to extend existing software modules with new functionality without needing to touch or re-compile the original source.
 
The Scala library includes a few typeclasses such as scala.math.Numeric and scala.math.Ordering, and Scalaz is all typeclasses.

Scala enables the typeclass pattern using traits and implicits, and whilst Scala’s implementation is more verbose than Haskell’s, it comes with greater flexibility. Haskell only allows a single typeclass instance globally, whereas Scala allows any number to be available.

Furthermore, Scala allows default implementations to be made available if no others can be found.
For a deeper understanding see the references at the bottom of the blog.

Example
(You can copy and run this code in your favorite IDE like IntelliJ/Eclipse ....) 

package test.home

/*
 * The trait defines a concept which in this case is a transformer  that transforms a type T into a R.
 */
trait Transformer[T, R] {
  def transform(t: T): R
}

/*
 * This is a companion object for the typeclass giving default implementations for the typeclass.
 * These implementations are found after local implicits, so you can still override the default
 * behaviour. For more about the search order see [3].
 */
object Transformer {
  implicit object IntToStringTransformer extends Transformer[Int, String] {
      def transform(t: Int) = {
        println("I m in IntToStringTransfer");
        t.toString
      }
    }
}

// This is something that makes use of the typeclass
trait Transform {

  // The implicit Transformer, transformer, supplies an appropriate transformer for the method
  def transformTrait[T, R](t: T)(implicit transformer: Transformer[T, R]): R = {
     println("I m in transformTrait()");
    transformer.transform(t)
  }
}

// These examples will drop back to the default implementations in the Transformer's companion object
object ExampleWithDefaults extends App with Transform {
  println(transformTrait(5))
}


//Output would be
I m in transform()
I m in IntToStringTransfer
5

Hope I am able to resolve your confusion about typeclass in scala

Wednesday, 20 January 2016

Lift Web Framework - Hello World

A step by step process to create a lift web project. There are 2 ways to do this - 

1. Download and Run Lift :
To install and run Lift, the only prerequisite is to have Java 1.5 or later installed.(Preferred 1.8)
Instructions for installing Java can be found here.
Once you have Java, the following instructions will download, build, and start a basic
Lift application.

For Windows :
• Visit http://liftweb.net/download and locate the link to the most recent ZIP version
of Lift 2.6 and save this to disk.
• Extract the contents of the ZIP file.
• Navigate in Explorer to the extracted folder, and once inside, navigate into sca‐
la_210 and then lift_basic.
• Double-click sbt.bat to run the build tool; a Terminal window should open.
• Required libraries will be downloaded automatically.
• At the SBT prompt (>), type container:start .
• You may find Windows Firewall blocking Java from running. If so, opt to “allow
access.”
• Start your browser and go to http://127.0.0.1:8080/
• When you’re done, type exit at the SBT prompt to stop your application from
running

2. Create project using SBT :
If you want to create the lift web project without using the ZIP files, then follow the below steps.
First of all, you will need to configure SBT and the Lift project yourself. We need only five small files for creating the project.

a. First, create an SBT plugin file at project/plugins.sbt (all file names are given relative to the project root directory):

         
addSbtPlugin("com.earldouglas" % "xsbt-web-plugin" % "0.9.0")
This file tells SBT that you will be using the xsbt-web-plugin and chooses the correct
version based upon your version of SBT.


b. Next, create an SBT build file, build.sbt:

   
organization := "org.krishna.com"

name := "Lift_Using_SBT"

version := "0.1-SNAPSHOT"

scalaVersion := "2.11.0"

seq(com.github.siasia.WebPlugin.webSettings :_*)

libraryDependencies ++= {
val liftVersion = "2.6"
Seq(
"net.liftweb" %% "lift-webkit" % liftVersion % "compile",
"org.eclipse.jetty" % "jetty-webapp" % "8.1.7.v20120910" %"container,test",
"org.eclipse.jetty.orbit" % "javax.servlet" % "3.0.0.v201112011016" %
"container,compile" artifacts Artifact("javax.servlet", "jar", "jar")
)
}

Feel free to change the various versions, though be aware that certain versions of Lift
are only built for certain versions of Scala.
Now that you have the basics of an SBT project, you can launch the sbt console. It should
load all the necessary dependencies, including the proper Scala version, and bring you
to a prompt.

c. Next, create the following file at src/main/webapp/WEB-INF/web.xml:

<!DOCTYPE web-app SYSTEM "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<filter>
<filter-name>LiftFilter</filter-name>
<display-name>Lift Filter</display-name>
<description>The Filter that intercepts Lift calls</description>
<filter-class>net.liftweb.http.LiftFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>LiftFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>

The web.xml file tells web containers, such as Jetty as configured by xsbt-web-plugin ,to pass all requests on to Lift.

d. Next, create a sample index.html file at src/main/webapp/index.html for our Lift app to
load. For example:

<!DOCTYPE html>
<html>
<head>
<title>Lift using SBT</title>
</head>
<body>
<h1>Welcome, you now have a working Lift installation</h1>
</body>
</html>
e. Finally, set up the basic Lift boot settings by creating a Boot.scala file at src/main/scala/bootstrap/liftweb/Boot.scala. The following contents will be sufficient:

package bootstrap.liftweb
import net.liftweb.http.{Html5Properties, LiftRules, Req}
import net.liftweb.sitemap.{Menu, SiteMap}
/**
* A class that's instantiated early and run. It allows the application
* to modify lift's environment
*/
class Boot {
def boot {
// where to search snippet
LiftRules.addToPackages("org.knoldus.com.Lift_Using_SBT")
// Build SiteMap
def sitemap(): SiteMap = SiteMap(
Menu.i("Home") / "index"
)
// Use HTML5 for rendering
LiftRules.htmlProperties.default.set((r: Req) =>
new Html5Properties(r.userAgent))
}
}
You have a working web lift project
To run the application, follow below command : 
sbt ~container:start
To browse the application, open http://localhost:8080
 
 To get the sample code, just clone the project from here


3 Cheers !!!


Monads in Scala

Monads belongs to Advance Scala   concepts. It  is not a class or a trait; it is a concept. It is an object which covers other object. A Mon...