Posts

sealed keyword in Scala

Image
sealed classes or traits can only be extended within the same file where it is defined. This is especially useful while creating the Algebraic Data Types.

Here are some of the characteristics of sealed traits

sealed traits should be extended within the same file so that the compiler knows all the possible subtypes otherwise the compiler can emit warnings if a match/case expression is not exhaustiveit cannot be extended anywhere else the same fileshould only be used if all the subtypes are early known in advance.this can be a way of creating something like an enum in Java

we can see the use of sealed traits in scala's Option like

sealedtraitOption[+A] finalcaseclassSome[+A] extendsOption[A] objectNoneextendsOption[Nothing]
so if we use these traits with pattern matching like this then we will get a compile error saying
Warning: match may not be exhaustive. It would fail on the following input: None

opt match { caseSome(a) =>"hello" }
and another benefit of using thi…

object keyword in scala

Image
The object keyword in scala creates a new singleton type, similar to the singleton class in Java i.e. its instance cannot be created twice and only has a single named instance. It's just like creating a new instance of the anonymous class in Java. Scala doesn't have a static concept. So scala creates a singleton object to provide an entry point for your program execution. If you don't create a singleton object, your code will compile successfully but will not produce any output. Methods declared inside Singleton Object are accessible globally. A singleton object can extend classes and traits.

objectSingleton{ def main(args:Array[String]){ //no object creation is needed here SingletonObject.hello() } objectSingletonObject{ def hello(){ println("Hello, This is Singleton Object") } }
Output:
Hello, This is Singleton Object


In scala, when we have a class with the same name as a singleton object, it is called as a compani…

Akka Actors in Java - Part 1

Image
Whenever we are dealing with the large and enterprise applications we always need to focus more on synchronizations and locks. This stuffs are more complex and also is time-consuming. But with Akka, we can easily write asynchronous code without the need for locks and synchronization. Akka is based on the message-driven terminology so that we don't need to wait for a return value instead the receiver will reply the sender with a message that will contain the result. And all actors are monitored by the parents so that it will also be easier to notify and stop the actors if the failure happens. In order to use Actors in our system lets first add akka-actor dependency in our pom.xml

<dependencies><dependency><groupId>com.typesafe.akka</groupId><artifactId>akka-actor_2.12</artifactId><version>2.5.11</version></dependency></dependencies>
//As we discussed all the actors will be in the hierarchy so lets create first the actor sys…

Functional Programming in Java - Part 1

Image
Let us Create a simple Class which validates the email. But we will start from creating in the classical java way.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34package advance.emailValidation; importjava.util.regex.Pattern; /** * Created by ypokhrel on 12/27/2017. */publicclassEmailValidator { privatestaticfinal String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"; finalstatic Pattern emailPattern = Pattern.compile(EMAIL_PATTERN); staticvoidtestMail(String email){ if(emailPattern.matcher(email).matches()){ sendVerification(email); }else{ logError(email); } } staticvoidsendVerification(String s){ System.out.println("Email verified and send to : " + s); } privatestaticvoidlogError(String s){ System.out.println(…

Stopping the Actor in Akka

Image
What if we want to stop the actor's in Akka. There are various ways to stop the Actor which we will discuss in this tutorial. But the basic ways are calling the actorSystem.stop(anActor) and context.stop(childActor).
We will use the second one if we need to stop the actor from inside the another actor. An actor can also stop itself by calling the context.stop(self)

Eg:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24packagestopimportakka.actor.{Actor,ActorSystem,Props}/** * Created by yubrajpokharel on 12/13/17. */objectstopMessage//extends App{val system =ActorSystem("normalStop")val actor = system.actorOf(Props[MyActor], name ="myactor") actor !Message system.stop(actor) system.terminate()}caseobjectMessageclassMyActorextendsActor{def receive ={caseMessage=> println(s"Actor get a call to act")case_=> println("Opps wrong number")}}
The other ways to stop actors are PoisionPill or gracefulStop.
let us dis…

Communication between two Actor's In scala

Image
In order to understand the commutation between two actors lets take an example of pingpong app which uses two actors name Ping and Pong.

importakka.actor._/** * Created by yubrajpokharel on 12/11/17. */caseobjectPingMessagecaseobjectPongMessagecaseobjectStartMessagecaseobjectStopMessageclassPing(pong:ActorRef) extendsActor{ var count =0def incrementAndPrint {count+=1; println("ping")} overridedef receive = { caseStartMessage=> incrementAndPrint pong ! PingMessagecasePongMessage=> incrementAndPrint if(count > 90) { sender ! StopMessage println("ping stopped") context.stop(self) }else{ sender ! PingMessage } case_=> println("ping got something unexpected") } } classPongextendsActor{ overridedef receive = { casePingMessage=> println(" pong") …

Creating Actor in Akka

Image
In Scala, we can create an Actor by extending the akka.actor.Actor class and writing the receive method in that class. Normally we will write the receive method by using the case statement that will allow the actor to respond t the different type of the messages it receives.

lets first create a project using the SBT name HelloAkka. Let's define our necessary resolver and dependency resolver information in the build.sbt file which looks like this.

name := "HelloAkka"

version := "1.0"

scalaVersion := "2.12.1"

resolvers += "Typesage Repository" at
    "http://repo.typesafe.com/typesage/releases/"

libraryDependencies += "com.typesafe.akka" %% "akka-actor" % "2.4.12"

if you are new to sbt don't worry it just like a maven or gradle which is esp build for scala and with much more features

Now lets write our first HelloAkka class

importakka.actor.{Actor, ActorSystem, Props} /** * Created by yubrajpokharel on 1…