define default named arguments in terms of other arguments in scala -
i have case class stores 3 tied parameters. i'd define companion object may build class 2 parameters, looks sample below, incorrect:
def test(start : float = end - duration, duration : float = end - start, end : float = start + duration) { require( abs(start + duration - end) < epsilon ) ... } val t1 = test(start = 0f, duration = 5f) val t2 = test(end = 4f, duration = 3f) val t3 = test(start = 3f, end = 5f)
what tricks may use similar usage syntax?
you can use type-classes:
// represents no argument object noarg // resolves start, duration, stop trait durationres[a,b,c] { def resolve(s: a, d: b, e: c): (float, float, float) } object durationres { implicit object startendres extends durationres[float, noarg.type, float] { def resolve(s: float, d: noarg.type, e: float) = (s, e-s, e) } implicit object startdurres extends durationres[float, float, noarg.type] { def resolve(s: float, d: float, e: noarg.type) = (s, d, s+d) } // etc. } def test[a,b,c](start: = noarg, dur: b = noarg, end: c = noarg) (implicit res: durationres[a,b,c]) { val (s,d,e) = res.resolve(start, dur, end) // s start, d duration, e end } test(start = 1f, end = 2f)
this way type-safe , cannot call like:
test(start = 1f)
or even
test()
Comments
Post a Comment