scala - What API for optional case class creation matches common developer expectations -
what api best use point of view of obviousness optional case class creation?
suppose have case class
case class position(position: int)
and position should never outside range [0, 18]. additionally want fp friendly argument cannot rejected exception when constraint have been violated.
is there better approach uses factory method result in option,
object position { def apply(position: int): option[position] = if (in range) some(position(position)) else none }
when called not clear option returned
val p = position(99)
would better?
object position { def maybe(position: int): option[position] = if(in range) some(position(position)) else none }
then usage becomes,
val p = position.maybe(99)
but maybe
boilerplate clarify result type.
this solution went based on linked duplicate answer,
case class port private(portnumber: int) object port { private val validrange = range(0, 65535+1) def opt(portnumber: int): option[port] = if (validrange contains portnumber) some(port(portnumber)) else none }
opt
selected instead of fromint
, make
or create
because gives hint result option[t]
.
Comments
Post a Comment