Scala - Define a type for Either for compactness or write it explicitly for readability?

In Scala, I can have:

trait Api { def someApiCall: Either[Failure, GoodResult]; } 

or

 object SomeObject { type SomeResult = Either[Failure, GoodResult] } trait Api { def someApiCall: SomeObject.SomeResult; } 

where the first describes in more detail the type of result and, therefore, it is easier to read, but includes the repeated inclusion of Either [...] again and again in different implementations. This is decided in the latter, but then the reader cannot do much about the results at a glance.

If the return type was Option instead of Either , I naturally stuck to the old version. For more complex types with many type parameters, the second will be more beneficial. Either is somewhere in the middle of the field.

The feeling of my feeling is that in the end the latter is more convenient. What do you think? Is there any practice in this regard?

+4
source share
1 answer

Make one of

  • Declare it explicitly as Either[X, Y] .
  • Declare it as MaybeResult[Y] (for type MaybeResult[A] = Either[Failure, A] )

Honestly, even then I declare this explicitly. The advantage # 2 (over your suggestion) is that with the standard Failure type (maybe Exception or List[String] ) you do not need to declare separate type aliases wherever you want to use this.

The advantage of using Either is that the user API is 100% clear . However, I would take another step and use Scalaz Validation :

 def someApiCall : ValidationNEL[String, Result] 

The advantage is that Validation can be arranged in ways that are not (otherwise they are isomorphic types). For instance:

 def a(i : Int) : ValidationNEL[String, Float] def b(f : Float) : ValidationNEL[String, Boolean] 

Then you can create:

 a(1) >>= b //ValidationNEL[String, Boolean] 

Same:

 scala> def a(i : Int) : ValidationNEL[String, Float] = error("") a: (i: Int)scalaz.Scalaz.ValidationNEL[String,Float] scala> def b(f : Float) : ValidationNEL[String, Boolean] = error("") b: (f: Float)scalaz.Scalaz.ValidationNEL[String,Boolean] scala> lazy val c = a(1) >>= b c: scalaz.Validation[scalaz.NonEmptyList[String],Boolean] = <lazy> 
+10
source

Source: https://habr.com/ru/post/1346207/


All Articles