Well the scala community has decided to deprecate view bounds in Scala. I suspect it might have to do with brevity. Full discussion can be viewed here
Well looks like most of the view bounds (<%)
can be converted to context bounds
. Lets see different strategies that can help us do the same. Suppose we have:
1 2 3 4 5 6 7 8 9 10 11 | scala> def foo[T < % Int](x : T) : Int = x foo : [T](x : T)( implicit evidence$ 1 : T = > Int)Int scala> implicit def a[T](n : T) = n match { | case x : String = > x.toInt | } warning : there were 1 feature warning(s); re-run with -feature for details a : [T](n : T)Int scala> foo( "23" ) res 4 : Int = 23 |
To convert it to `context bound` we need to implicitly have something that does T => Int
. We could:
1 2 3 4 5 6 7 8 | scala> type L[X] = X = > Int defined type alias L scala> def goo[T : L](x : T) : Int = x goo : [T](x : T)( implicit evidence$ 1 : T = > Int)Int scala> goo( 23 ) res 2 : Int = 23 |
We could combine the type declaration with the function definition as:
1 2 3 4 | scala> def goo[T : ({ type L[X] = X = > Int}) # L](x : T) : Int = x goo : [T](x : T)( implicit evidence$ 1 : T = > Int)Int //quite cryptic though |
A more readable version:
1 2 3 4 5 | scala> def goo 2 [T](x : T)( implicit ev : T = > Int) : Int = x goo 2 : [T](x : T)( implicit ev : T = > Int)Int scala> goo 2 ( "12" ) res 8 : Int = 12 |
More generalized version:
1 2 3 4 5 6 7 8 9 10 11 | scala> def goo[E,T : ({ type L[X] = X = > E}) # L](x : T) : E = x goo : [E, T](x : T)( implicit evidence$ 1 : T = > E)E scala> def goo 2 [T, E](x : T)( implicit ev : T = > E) : E = x goo 2 : [T, E](x : T)( implicit ev : T = > E)E scala> goo( "1000" ) res 10 : String = 1000 scala> goo 2 ( "1000" ) res 11 : String = 1000 |
0 comments:
Post a Comment