scala - Is there there any difference or reason to prefer one of these function signatures? -
i don't think there's difference, or reason prefer 1 on other, wanted check...
def length(l: list[any]) def length[t](l: list[t])
if want length of list, there no difference you.
but if want operatations elements of list, there is.
val l = list(1, 2, 3, 4) def secondelementany(l: list[any]) = l.tail.head def secondelementgen[a](l : list[a]) = l.tail.head giving 2 functions , list, expect 2 list.
val secondany = secondelementany(l) val secondgen = secondelementgen(l) if print values console, spot no diference, if try cast them float example, error. secondany.tofloat tell us, secondany type of any , cannot use function tofloat on any.
in contrast secondgen.tofloat give float value.
the reason is, compiler aproximates full signatures follows.
def secondelementany(l: list[any]): = l.tail.head def secondelementgen[a](l: list[a]): = l.tail.head as can see return type of first function any, any whereas return type of second function depends on type of list. element of type. typesafe.
Comments
Post a Comment