Skip to content

Instantly share code, notes, and snippets.

@beranradek
Created June 13, 2013 10:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save beranradek/5772874 to your computer and use it in GitHub Desktop.
Save beranradek/5772874 to your computer and use it in GitHub Desktop.
// Ad 1) Type class trait ("utility" rozhraní, na které budou
// adaptovány konkrétní zdroje):
trait Resource[R] {
def hasChildren(res: R): Boolean
def children(res: R): Seq[R]
}
// Ad 2) Companion object s výchozími implicitními implementacemi
// type class traitu pro URL a File:
object Resource {
implicit object UrlResource extends Resource[URL] {
override def hasChildren(res: URL): Boolean = true
override def children(res: URL): Seq[URL] =
if (!hasChildren(res)) Seq()
else {
val linkExtractor = """ href="([^"]+)"""".r
val linesIter = Source.fromURL(res)("UTF-8").getLines
// println("Lines: " + linesIter)
val allLinks = for {
line <- linesIter
mathes <- linkExtractor.findAllIn(line).matchData
} yield mathes.group(1)
val urlLinks = allLinks.map {
x: String => Try { new URL(x) } }
.collect { case Success(url) => url }
urlLinks.toList
}
}
implicit object FileResource extends Resource[File] {
override def hasChildren(res: File): Boolean = res.isDirectory()
override def children(res: File): Seq[File] =
if (!hasChildren(res)) Seq()
else res.listFiles().toList
}
}
// Ad 3) Algoritmy/operace pracující se zdroji:
object ResourceOperations {
def listChildren[A](res: A)(implicit resHelper: Resource[A]): Seq[A] =
resHelper.children(res)
// Ta samá metoda implementovaná pomocí context bounds,
// což je jen "Syntactic sugar" umožňující vynechat druhý
// implicitní seznam parametrů. Musí existovat implicitní Resource
// definovaný pro typový parametr A:
def listChildrenUsingCtxBounds[A: Resource](res: A): Seq[A] = {
val resHelper = implicitly[Resource[A]]
resHelper.children(res)
}
// Použití:
def main(args: Array[String]) {
println("Children of URL: \n: " +
ResourceOperations.listChildren(
new URL("http://czechscala.com/")))
println("Children of File: \n: " +
ResourceOperations.listChildren(
new File(System.getProperty("user.dir"))))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment