What is a “context bound” in Scala?

后端 未结 4 1738
隐瞒了意图╮
隐瞒了意图╮ 2020-11-22 11:19

One of the new features of Scala 2.8 are context bounds. What is a context bound and where is it useful?

Of course I searched first (and found for example this) but

4条回答
  •  北荒
    北荒 (楼主)
    2020-11-22 11:55

    This is another parenthetical note.

    As Ben pointed out, a context bound represents a "has-a" constraint between a type parameter and a type class. Put another way, it represents a constraint that an implicit value of a particular type class exists.

    When utilizing a context bound, one often needs to surface that implicit value. For example, given the constraint T : Ordering, one will often need the instance of Ordering[T] that satisfies the constraint. As demonstrated here, it's possible to access the implicit value by using the implicitly method or a slightly more helpful context method:

    def **[T : Numeric](xs: Iterable[T], ys: Iterable[T]) = 
       xs zip ys map { t => implicitly[Numeric[T]].times(t._1, t._2) }
    

    or

    def **[T : Numeric](xs: Iterable[T], ys: Iterable[T]) =
       xs zip ys map { t => context[T]().times(t._1, t._2) }
    

提交回复
热议问题