In keeping with the uniform principle of Scala, types can defined as variables. This is useful for several reasons but this topic covers a cool/fun effect of having types be declared like variables. Type Aliasing. In the example below an alias | is created for the Either class. This allows the | to be used in place of Either.
- // Start of example 1. creating the type alias
- // define the | type
- scala> type |[A,B] = Either[A,B]
- defined type alias $bar
- // If a Type has 2 parameters it can be used in operator form
- scala> Array[Int | Long](Left(5),Right(12L))
- res0: Array[|[Int,Long]] = Array(Left(5), Right(12))
- // start of example 2. Simplify creation of an Array (or other collection) of either
- scala> implicit def makeLeft[A,B](a:A):Either[A,B] = Left(a)
- makeLeft: [A,B](a: A)Either[A,B]
- scala> implicit def makeRight[A,B](b:B):Either[A,B] = Right(b)
- makeRight: [A,B](b: B)Either[A,B]
- // Since there are implicits to convert to Right and Left the values in the Array will be wrapped
- // automatically. Makes the syntax MUCH cleaner and easier to read.
- scala> Array[Int|String](5,"Wurst",123,2,6)
- res1: Array[|[Int,String]] = Array(Left(5), Right(Wurst), Left(123), Left(2), Left(6))
I do wonder why the makeLeft and makeRight implicits did not cause an ambiguity error. After all, what's to say Int is the left and String is the right?
ReplyDeleteThe information that determines if the value is a Left or a Right is inferred from the Array type signature: Array[Int | String] the type inferencer is able to determine that the string is the Right and vice versa. Pretty powerful.
ReplyDeleteI wouldn't necessarily call this type inferencing. As far as I understand implicit conversions. Since 5 is not of type Either[Int|String], it will look for implicits before aborting with a compile error. It will find the that the only implicit which takes in the right argument (both in this case) and the produces the correct type is makeLeft (because makeRight would produce Either[String|Int], not Either[Int, String]. Symetrically for any String argument in the Array constructor.
ReplyDeleteThere is absolutely not ambiguity as far as I am concerned and this all naturally occurs from following the simple implicit conversion rules, I wouldn't exactly consider this behaviour to be type inferencing.
Nice post btw, do any of you have any ideas on why makeLeft and makeRight are not part of "language.implicitConversions"?