What is a “context bound” in Scala?

后端 未结 4 1711
隐瞒了意图╮
隐瞒了意图╮ 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:41

    (This is a parenthetical note. Read and understand the other answers first.)

    Context Bounds actually generalize View Bounds.

    So, given this code expressed with a View Bound:

    scala> implicit def int2str(i: Int): String = i.toString
    int2str: (i: Int)String
    
    scala> def f1[T <% String](t: T) = 0
    f1: [T](t: T)(implicit evidence$1: (T) => String)Int
    

    This could also be expressed with a Context Bound, with the help of a type alias representing functions from type F to type T.

    scala> trait To[T] { type From[F] = F => T }           
    defined trait To
    
    scala> def f2[T : To[String]#From](t: T) = 0       
    f2: [T](t: T)(implicit evidence$1: (T) => java.lang.String)Int
    
    scala> f2(1)
    res1: Int = 0
    

    A context bound must be used with a type constructor of kind * => *. However the type constructor Function1 is of kind (*, *) => *. The use of the type alias partially applies second type parameter with the type String, yielding a type constructor of the correct kind for use as a context bound.

    There is a proposal to allow you to directly express partially applied types in Scala, without the use of the type alias inside a trait. You could then write:

    def f3[T : [X](X => String)](t: T) = 0 
    

提交回复
热议问题