Created
January 4, 2015 03:16
-
-
Save bvenners/855f7072e2c913b5081e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Here's a typeclass trait for types that can be sliced | |
trait Slicing[T] { | |
def slice(o: T, from: Int, until: Int): T | |
} | |
// The companion object provides impicits for String and Vector | |
object Slicing { | |
implicit val slicingNatureOfString: Slicing[String] = | |
new Slicing[String] { | |
def slice(s: String, from: Int, until: Int): String = s.substring(from, until) | |
} | |
implicit def slicingNatureOfVector[E]: Slicing[Vector[E]] = | |
new Slicing[Vector[E]] { | |
def slice(v: Vector[E], from: Int, until: Int): Vector[E] = v.slice(from, until) | |
} | |
} | |
// Example has a genericSlice method that will work with any type T | |
// for which an implicit Slicing[T] exists. | |
object Example { | |
def genericSlice[T: Slicing](o: T, from: Int, until: Int): T = { | |
val slicing = implicitly[Slicing[T]] | |
slicing.slice(o, from, until) | |
} | |
} | |
// You can, therefore, slice a String with genericSlice | |
scala> Example.genericSlice("one two three", 4, 7) | |
res1: String = two | |
// And a Vector | |
scala> Example.genericSlice("one two three".toVector, 4, 7) | |
res2: Vector[Char] = Vector(t, w, o) | |
// But not a List | |
scala> Example.genericSlice("one two three".toList, 4, 7) | |
<console>:12: error: could not find implicit value for evidence parameter of type Slicing[List[Char]] | |
Example.genericSlice("one two three".toList, 4, 7) | |
^ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment