scala - Should I use type, if my "extends AnyVal" has not methods? -
the internet not able answer question yet. 2 lines seem interchangeable me:
type meter = double class meter(val d: double) extends anyval if meter not have methods, should use type instead? what's difference?
what's difference?
well, obvious thing first type alias, nothing more. latter attempt unroll wrapping class , use underlying primitive directly. but, there cases anyval can't unwrapped stated in documentation. example, assume wanted pass meter polymorphic function:
def identity[t](t: t): t = t passing meter in allocate instance:
scala> class meter(val d: double) extends anyval defined class meter scala> def identity[t](t: t): t = t identity: [t](t: t)t scala> :se -xprint:typer scala> identity(new meter(1.0)) // shortened brevity private[this] val res0: meter = $line4.$read.$iw.$iw.identity[meter](new $line3.$read.$iw.$iw.meter(1.0)); <stable> <accessor> def res0: meter = $iw.this.res0 on other hand, type meter yield double:
scala> type meter = double defined type alias meter scala> val m: meter = 1.0 m: meter = 1.0 scala> def identity[t](t: t): t = t identity: [t](t: t)t scala> :se -xprint:uncurry scala> identity(m) private[this] val res1: double = $line5.$read.$iw.$iw.identity[double]($line4.$read.$iw.$iw.m()); <stable> <accessor> def res1(): double = $iw.this.res1 another sensitivity if allocate array[meter], instance need allocated.
there differences between two. 1 should use? usually, depends. if type safety of outter importance , don't mind edge cases 1 occurs allocation, go class. if have rather complex type want abstract over, example either[string, a] want make type simpler, perhaps type foo[a] = either[string, a] simpler understand , more intuitive.
Comments
Post a Comment