scala - What's the difference between view bounds and type bounds implementing evidence keyword? -
i'm not sure if i've got terminology down right in title, what's difference between this:
class container[a <% int] { def addit(x: a) = 123 + x } and this:
class container[a](value: a) { def addit(implicit evidence: =:= int) = 123 + value } i suppose question why use 1 form of type bound on another? matter of being able apply type bound @ different parts of code (eg in parameter list vs body)?
also, documents methods may ask "evidence" type rather using other objects type checking provide second code snippet. kind of evidence referring to?
note: regarding this article on advanced types.
view bounds when want use type viewable type. in example, want a viewable int. , means want any implicit conversion in scope a => int.
ie. same as:
class container(implicit evidence: => int) { def addit(x: a) = 123 + x } they deprecated. should reason enough avoid them.
type bounds not correct term second example. strictly bounding types of parameter above or below. type bound this:
class container[a <: int] { def addit(x: a) = 123 + x } in example a must strictly bounded above int. implicit conversions cannot apply.
i'm not sure if there's name second example, differs view bounds in requires instance of type class =:= seen here. similar view bounds in =:= witnesses a same int, , therefore allows a converted explicitly int. however, requires instance of type class =:=[a, int] exist, , not any implicit conversion a => int.
your 2 examples kind of fundamentally different though. first requires view bound on class itself, second requires type evidence on method. is, first example not allow instances of container[string] exist @ (without implicit conversion available), second 1 does. second example happily allows construct container[string], not let use addit method, unless have evidence string =:= int.
by evidence mean either implicit conversion type we're interested in (a => int), or instance of type class =:= witnesses equality. types same, have automatically generated in predef (earlier link).
Comments
Post a Comment