How do I write a shorthand for a datatype in Scala -
how write shorthand datatype? example. lets instead of list[integer]
, rather type integers
instead of this
def processnumbers(input:list[integer]):list[integer] = ...
to
def processnumbers(input:integers):integers = ...
is possible?
thanks
yes, can type alias.
type integers = list[int] // scala.int preferred on java.lang.integer
that being said, isn't use them. list[int]
clear other scala developers, wheres type integers
provides no information , detract readability of code on time.
a use of type aliases improve code's readability though like
type userid = int def processusers(ids: list[userid]): foo
in case provides information reader vs
def processusers(ids: list[int]): foo
using kind of type alias allow gradually make code more type-safe on time changing definition type alias value class.
case class userid(value: int) extends anyval
you won't need change method signatures of having "userid
", let compiler assist in making sure don't like
val ids: list[int] = getblogpostids() val foo = processusers(ids) // oops, ints blog posts, not users
using value class approach, mistake becomes compiler error. used pervasively adds quite lot of guidance in writing correct code.
val ids: list[blogpostid] = getblogpostids val foo = processusers(ids) // compile error; blogpostid != userid
Comments
Post a Comment