The post Scala Microservices appeared first on .

]]>

http://www.scalamicroservices.com/

The post Scala Microservices appeared first on .

]]>The post Monoid & MonoidK appeared first on .

]]>In continuation to previous post.

There is no documentation for MonoidK (Monoid for higher Kinds) on the cats site, hence let me try explaining it. Though Monoid first.

`Monoid[T]` technically is a Semigroup with an `empty`/`Identity` function. i.e. There are two main properties:

- Associativity (From Semigroup)
- Identity

Roughly:

trait Monoid[T]{ /** combine is defined as: `(a combine b) combine c = a combine (b combine c)` */ def combine(x:T, y:T): T /** empty is defined as: `A o empty = empty o A = A` */ def empty : T }

An example:

implicit def intMonoid = new Monoid[Int]{ override def empty: Int = 0 override def combine(x: Int, y: Int): Int = x + y } Semigroup[Int].combine(1,2) // returns 3 implicit def listMonoid[T](implicit ev: Monoid[T]): Monoid[List[T]] = new Monoid[List[T]]{ override def empty: List[T] = List() override def combine(x: List[T], y: List[T]): List[T] = x ::: y } Semigroup[List[Int]].combine(List(1,2), List(3,4)) //gives List(1,2,3,4) implicit def optionMonoid[T](implicit ev: Monoid[T]) : Monoid[Option[T]] = new Monoid[Option[T]]{ override def empty: Option[T] = None override def combine(x: Option[T], y: Option[T]): Option[T] = x match { case Some(a) => y match { case Some(b) => Some(ev.combine(a, b)) case None => None } case None => y } } Semigroup[Option[Int]].combine(Option(1), Some(2)) //gives Option(3) //This is quite awesome in the sense, that it even works for its inner type automatically. It is same as: Semigroup.apply[Option[Int]](optionMonoid[Int](intMonoid)).combine(Option[Int](1), Some[Int](2)); //Many standard Monoids are available under below imports import cats._ import cats.std.all._ Monoid[String].combineAll(List()) Monoid[Map[String,Int]].combineAll(List(Map("a" -> 1, "b" -> 2), Map("a" -> 3))) //Returns Map(b -> 2, a -> 4)

MonoidK is a Monoid for a kind (K stands for Kind). This is how it is roughly defined:

trait MonoidK[F[_]]{ def combine[A](x:F[A], y:F[A]): F[A] def empty[A] : F[A] }

We basically define the typeconstructor while declaring the `MonoidK` object and later define the type argument while calling `combine`. Its like you are working on the container and work based on its proper type provided later. One important thing to notice is that, you dont really stand a chance to work in nested. Example:

implicit def Ksemi[T]: SemigroupK[Option] = new SemigroupK[Option]{ override def combine[A](x: Option[A], y: Option[A]): Option[A] = x orElse y } SemigroupK[Option].combine(Option(1), Option(2)) // returns Option(1) implicit def listK : MonoidK[List] = new MonoidK[List] { override def empty[A]: List[A] = List() override def combine[A](x: List[A], y: List[A]): List[A] = x ::: y } MonoidK[List].combine(List(1,2,3),List(4))

When we define `SemigroupK[Option]`, we actually provide the type constructor. Doing so, leaves us no chance to provide implicit Monoid for its type parameter. So the behavior of `combine` is purely based on the container rather than the type argument.

The post Monoid & MonoidK appeared first on .

]]>The post Scala World appeared first on .

]]>Well I am back from Scala World. The most awesome scala conference of its keep!

Not only were there awesome speakers: Paul Phillips (you have to admit, its not that easy finding Paul give scala talks now), Runar Bjarnason (found his talk to be the best), Jon Pretty (of-course), Bill Venners, Michael Pilquist, Miles Sabin, Erik Osheim, Sebastien Doeraene of Scala.js fame, Lars, Dmitry of dotty, Roland Kuhn, Adriaan Moors, John De Goes, Daniel Spiewak etc etc etc. In short, if the roof came down you all could have gone back to using Java!

So again, not only where there awesome speakers but it was very very personal. The two awesome treks with speakers and other fellow members, the dinner on day-1 with people seated in an alphabetical order (I had Michael Pilquist and Iulian Dragos on my table), the ease of interaction with all the super stars around. It was damn good! Probably the most personal conference I have ever been to.

You can view all the talks on the youtube channel here. And yes, here is me introducing Miles for his talk

PS: Thanks to super awesome Jon Pretty for having me over. I definitely owe you one.

The post Scala World appeared first on .

]]>The post Happy Types appeared first on .

]]>I had prepared this monthâ€™s monthly newsletter on generics in Java for my team. It may not be the one ring, but might help you gaining a step, to become the one ring in `Generics` in Java (In case if you are not already). It can be accessed here.

Table of Contents and brief summary:

- Type Erasure: Here we see what it means especially in Java.
- Reification

Variance

Here we introduce some terms: Co-Variance, Contra-Variance, In-variance.Â And then explain what do they actually mean.

- We observe the true strengths of `? extends` and `? super` and when should you be using what.
- Almost all different case one can think of.

Please let me know in case you disagree with something.

PS:Â The booklet has been generated using Scalatex developed by Li Haoyi. You might want to look at it. Its easier to setup than Jekyll and certainly more expressive than WordPress. And provides compile time *like* type safety.

The post Happy Types appeared first on .

]]>The post Cats appeared first on .

]]>Cats is a simple and concise functional programming library for Scala. It appeals to me for its compactness and simpler class hierarchy.

I have no formal education in category theory. But I am a student of theoretical Mathematics and have studied Abstract Algebra. Though I am not aware of formal category theory terms, I will try converting them to simple set theory.

Category theory is concerned with study of algebraic structures. Algebraic system can be described as a set of objects together with some operations for combining them. Example’s can be vectors, groups, fields etc. Or even Sets.

The aim of this blog post is to explain `cats`

first in a very simple lucid way. And they try putting it in code. I will be using some terms:

**Universe**: For example: Integer-Universe would imply a universe containing integers or set of integers. Think of it as our infinite terrestrial universe which contains milky way which contains solar system and ultimately planets.**Space/Type**: A set of elements corresponding to a property. Space exists in universe. You can think Space as a type in scala.

Let `A`

and `B`

be space in some universe. And there exists a function `f` from A to B. Â Then Functor for `X` universe is a mapping from (mapping of space A in X universe) `X(A)` to (mapping of space `B` in universe `X`) `X(B)`

Now what does this mean in scala world? Say we have a function `f` that tells us how to convert from type A to type B. So `f` does `Int => String`.

Now we want a mechanism to convert elements of another universe, say `Option` universe. First we need a mechanism to convert from space `A` in our universe to `Option(A)` (Space A in Option universe). We will see how it happens later below (Applicative).

So now some how we have mapped A to Option universe. Lets call it `Option(A)` space. We wish to convert from space `Option(A)` to space `Option(B)` (i.e. we need to `Option[Int] => Option[String]`) (Or F[Option] in above image)

Functors are exactly for this purpose with `map` being its flagship method:

trait Functor[F[_]] { self => def map[A, B](f: F[A])(f: A => B): F[B] }

implicit val OptionFunctor = new Functor[Option] { override def map[A, B](fa: Option[A])(f: (A) => B): Option[B] = fa map f } Functor[Option].map(Some(1))(x => x*13) Functor[Option].map(Some(1))(x => x.toString)

Functor[Option] is a mapping mechanism from space `Option(A)` to set `Option(B)` in Option universe. Think of it as:

We know how to convert from a space A to another space B in some universe. In another universe X, Functor of X lets us convert from X(A) to X(B)

So it lets you convert from `Option[Int] => Option[String]` or `Option[String] => Option[List[Int]]` etc. In short any space to any space in `Option` universe

**Lift:**

Lift is my favorite method in Functor.Â Notice with map,Â provided you have `Option[A]`, map converts to `Option[B]`. i.e. it consumes `Option[A]` object. But the conversion from `Option[A] => Option[B]` is just another function can be useful if it can be pass around as function. i.e. `F[X]` in above image.

def toStri(n:Int) = n.toString val lift: (Option[Int]) => Option[String] = Functor[Option].lift(toStri) lift(Some(1))

If you think, lift seems something like this:

val lift = Functor[Option].map _ //ignore map types

`lift` seems everything of a `map` but as a pure function. And thats how lift is implemented

def lift[A, B](f: A => B): F[A] => F[B] = x => map(x)(f)

For a function from Space A to Space B, lift provides a function in Universe X to convert from X(A) to X(B)

Now notice, using a Functor we can convert from X(A) to X(B), given a function A to B. But how do we convert an element x belonging to A, to an element in X(A)?

Applicative lets us do that:

implicit val OptionApplicative = new Applicative[Option] { override def pure[A](x: A): Option[A] = Option(x) override def apply[A, B](fa: Option[A])(f: Option[(A) => B]): Option[B] = ... } val op: Option[Int] = Applicative[Option].pure(1)

`pure` lets us convert an element from a universe to another. In above case, it lets us convert from element of type `Int` to `Option[Int]`. Applicative is an `Apply`

Apply is also a Functor.

def apply[A, B](fa: F[A])(f: F[A => B]): F[B]

Just instead of the function `f` which converts from `A => B`, you have `X(A => B)`. i.e. a function in X universe. Notice it is not `X[A] => X[B]`.

Lets have some more comprehensive example:

implicit val ListApplicative = new Applicative[List] { override def pure[A](x: A): List[A] = List(x) override def apply[A, B](fa: List[A])(f: List[(A) => B]): List[B] = fa.flatMap(x => f.map(y => y(x))) } val lsOp = Applicative[List].pure(2)

You ask the Applicative for `List` to convert an element 2 to something in `List` universe. i.e. `List(2)`

scala> val ls = Applicative[List].apply(List(1,2,3))(List(x => "a=>"+x, y => "b ==>"+y)) ls: List[String] = List(a=>1, b ==>1, a=>2, b ==>2, a=>3, b ==>3) scala> val ls2 = Applicative[List].apply2(List(1,2,3), List(4,5,6))(List((x:Int,y:Int) => x+" --a--> "+y, (x:Int,y:Int) => x+" --b--> "+y)) ls2: List[String] = List(1 --a--> 4, 1 --b--> 4, 2 --a--> 4, 2 --b--> 4, 3 --a--> 4, 3 --b--> 4, 1 --a--> 5, 1 --b--> 5, 2 --a--> 5, 2 --b--> 5, 3 --a--> 5, 3 --b--> 5, 1 --a--> 6, 1 --b--> 6, 2 --a--> 6, 2 --b--> 6, 3 --a--> 6, 3 --b--> 6)

implicit val OptionApplicative = new Applicative[Option] { override def pure[A](x: A): Option[A] = Option(x) override def apply[A, B](fa: Option[A])(f: Option[(A) => B]): Option[B] = fa.flatMap(x => f.map(y => y(x))) } scala> val comp= (Applicative[List] compose Applicative[Option]) comp: cats.Applicative[[Î±]List[Option[Î±]]] = cats.Applicative$$anon$1@168d1858 scala> comp.pure(12) res5: List[Option[Int]] = List(Some(12))

Compose is quite interesting. So say you have an Applicative for List universe and another Applicative for Option universe. By composing them, you get an Applicative for `List[Option]`. Calling pure convert’s 12 from Int to a List(Option(1)).

PS: Will keep updating with time

The post Cats appeared first on .

]]>The post Type-information of generic type for a Parametrized class appeared first on .

]]>Sometimes you feel that your code is world-class and deserves to be shared. There is one such class I have written for a personal project and find it to be extremely useful. You can view it here. Its called `CaptureType`

This class obtains the type information of the generic type and can be accessed in a type-safe manner. Some simple examples:

static void test1() { CaptureType<String> t1 = new CaptureType<String>() {}; equals(t1.getRawType(), String.class); } static void test2() { CaptureType<List<String>> t1 = new CaptureType<List<String>>() {}; equals(t1.getRawType(), List.class); equals(t1.getParamADT().getParameters().get(0).getRawType(), String.class); }

Little tougher:

static class Test4 extends CaptureType<List<String>> {} static void test4() { Test4 test4 = new Test4(); equals(test4.getParamADT().getRawType(), List.class); } static class PreTest6<S> extends CaptureType<S> {} static class Test6 extends PreTest6<Integer> { }

A really tough one:

class X<T> extends CaptureType<T> { } class Y<A, B> extends X<B> { } class Z<Q> extends Y<Q, Map<Integer, List<List<List<Integer>>>>> { } void test7(){ Z<String> z = new Z<>(); TypeADT param = z.getParamADT(); equals(param.getRawType(), Map.class); List<TypeADT> parameters = param.getParameters(); equals(parameters.get(0).getRawType(), Integer.class); equals(parameters.get(1).getRawType(), List.class); equals(parameters.get(1).getParameters().get(0).getRawType(), List.class); equals(parameters.get(1).getParameters().get(0).getParameters().get(0).getRawType(), List.class); equals(parameters.get(1).getParameters().get(0).getParameters().get(0).getParameters().get(0).getRawType(), Integer.class); }

This class captures information using Reflection. Sadly, it only obtain whatever reflection can provide. It captures generic types using the super token.

So in cases like:

class SomeClass<T> extends CaptureType<T>{} SomeClass<String> claz = new SomeClass<>();

It is impossible to obtain the type information as it is erased. `CaptureType` class will only work,

if the type is mentioned while declaring the Class (at any point in hierarchy). For example in:

class A<Z> extends CaptureType<Z>{} class B<E,T> extends A<T>{} class C <X,Y,Z> extends B<X, String> }

It is possible to obtain the type {@code String}, because it is mentioned at class level and can be mapped by following hierarchy. So `Z` in {@code A} is {@code String}

Please comment down your feedback. Even better an improvement :). I give as good as I get!

The post Type-information of generic type for a Parametrized class appeared first on .

]]>The post Parallel Streams!! appeared first on .

]]>I am always skeptical of using parallel streams in Java8. For simple reason:

You do not have control to decide the pool responsible for executing tasks. By default, common ForkJoinPool executes it.

So in short when you do:

stream.parallel().filter(x -> isPrime(x));

The common pool executes it. And you cannot let some other pool execute `filter` in a straight-forward manner. It gets really dangerous on large codebases where people stupidly using parallel streams. If any computation gets time taking or worse blocking, it impacts all the parallel streams because they all use the same pool.

Though there is a way to let your custom pool execute tasks, but it is insanely irritating (and breakable).

ForkJoinPool pool = new ForkJoinPool(4); int[] ans = pool.submit(() -> { return IntStream.range(1,1000000).parallel().filter(x -> isPrime(x)).toArray(); }).get(); public static boolean isPrime(int i){ System.out.println(Thread.currentThread()); return true; }

The above prints `Thread[ForkJoinPool-1-worker-0,5,main]`

rather than `Thread[ForkJoinPool.commonPool-worker-2,5,main]`

. Which means the subtasks are executed by our pool rather than the common pool. It seems magic because we haven’t requested the parallel stream to use our pool. This implicitly happens because of ForkJoinTask#doInvoke internals

private int doInvoke() { int s; Thread t; ForkJoinWorkerThread wt; return (s = doExec()) < 0 ? s : ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) ? (wt = (ForkJoinWorkerThread)t).pool.awaitJoin(wt.workQueue, this) : //else delegate to common pool }

Where it checks if the current thread is part of any pool, if so obtains reference to the pool and uses it. Else delegates to common pool.

I haven’t found documentation which suggests above behavior. Hence the behavior cannot be fully trusted.

The post Parallel Streams!! appeared first on .

]]>The post Constraint Argument to Multiple Types appeared first on .

]]>A lot of times while writing quick scripts (where I haven’t thought through well), I wish the compiler would be a bit lenient to allow any argument of different types. Like this:

class Animal def getInt(n: Any) : Int = n match { case x: Int => x case x: String => Integer.parseInt(x) case x: Animal => 42 }

Duck typing looks well. But its too lenient for me. I dont like the ability to do `getInt(new Object)`

. I wish I was allowed to do:

def getInt(n: Int || String || Animal) : Int = n match { case x: Int => ....

One very smart way of doing it can be:

sealed trait GetIntType[-T] object GetIntType{ implicit object IntType extends GetIntType[Int] implicit object StringType extends GetIntType[String] implicit object AnimalType extends GetIntType[Animal] } class Dog extends Animal def getInt[T : GetIntType](n: T) : Int = n match { case x: Int => x case x: String => Integer.parseInt(x) case x: Animal => 42 } scala> getInt(1) res7: Int = 1 scala> getInt("1") res8: Int = 1

It works because, the compiler constraint is from the availability of implicit objects in `GetIntType` companion object. The context bound `implicit def f: GetIntType[T]`

by default searches for implicit objects inside companion object of `GetIntType`. So now not only you can do this:

scala> getInt(new Animal) res5: Int = 42</pre>

But also this:

scala> getInt(new Dog) res6: Int = 42

It works because `GetIntType` is contra-variant. Which means if `Dog <: Animal`

then `GetIntType[Animal] <: GetIntType[Dog]`

.

But I still find the above tedious. And too much baggage code.

The post Constraint Argument to Multiple Types appeared first on .

]]>The post Hack Puzzle – 1 appeared first on .

]]>I have been thinking for quite some-time to build a puzzle. I think I have built an awesome one and hope everyone finds it awesome to hack

You can download the jar from here.

Aim:

- Make the programÂ
*terminate gracefully*

To run:

- java -jar DeadLock2.jar

If successfully run it will output:

Oops there is a deadlock. Please solve the deadlock to make me move forward.

Rules:

- You cannot replace any of the jar contents with your files
- You cannot recompile any of the classes in jar and replace them
- You are permitted to alter/modify the contents of the jar/class files
- You are permitted to add or use any external library to solve it

If successfully solved, the program prints the below:

Puzzle Soved!! Congratulations you have solved the puzzle.

Comment below the tools you used and time it took to solve. Happy Hacking

The post Hack Puzzle – 1 appeared first on .

]]>The post Replace View Bounds appeared first on .

]]>Well the scala community has decided to deprecateÂ view bounds in Scala. I suspect it might have to do with brevity. Full discussion can be viewedÂ here

Well looks like most of the `view bounds (<%)`

can be converted to `context bounds`

. Lets see different strategies that can help us do the same. Suppose we have:

scala> def foo[T <% Int](x: T):Int = x foo: [T](x: T)(implicit evidence$1: T => Int)Int scala> implicit def a[T](n:T) = n match { | case x:String => x.toInt | } warning: there were 1 feature warning(s); re-run with -feature for details a: [T](n: T)Int scala> foo("23") res4: Int = 23

To convert it to `context bound` we need to implicitly have something that does `T => Int`

. We could:

scala> type L[X] = X => Int defined type alias L scala> def goo[T : L](x: T):Int = x goo: [T](x: T)(implicit evidence$1: T => Int)Int scala> goo(23) res2: Int = 23

We could combine the type declaration with the function definition as:

scala> def goo[T : ({type L[X] = X => Int})#L](x: T):Int = x goo: [T](x: T)(implicit evidence$1: T => Int)Int //quite cryptic though

A more readable version:

scala> def goo2[T](x: T)(implicit ev: T => Int):Int = x goo2: [T](x: T)(implicit ev: T => Int)Int scala> goo2("12") res8: Int = 12

More generalized version:

scala> def goo[E,T : ({type L[X] = X => E})#L](x: T):E = x goo: [E, T](x: T)(implicit evidence$1: T => E)E scala> def goo2[T, E](x: T)(implicit ev: T => E):E = x goo2: [T, E](x: T)(implicit ev: T => E)E scala> goo("1000") res10: String = 1000 scala> goo2("1000") res11: String = 1000

The post Replace View Bounds appeared first on .

]]>