Skip to content

@beranradek /typedclass.scala
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
package dojo
import java.net.URL
import java.io.File
import scala.io.Source
import java.io.InputStream
import scala.util.Try
import scala.util.Success
trait Resource[R] {
def content(res: R): String
def children(res: R): List[R]
def hasChildren(res: R): Boolean
}
object Resource {
implicit object UrlResource extends Resource[URL] {
val linkExtractor = """ href="([^"]+)"""".r
override def content(res: URL): String = {
res.getContent() + ""
}
override def children(res: URL): List[URL] = {
val links = (for {
line <- Source.fromURL(new URL("http://www.typesafe.org/"))("UTF-8").getLines
it <- linkExtractor.findAllIn(line).matchData
} yield {
it.group(1)
}).map { x: String => Try { new URL(x) } }.collect { case Success(url) => url }
links.toList
}
override def hasChildren(res: URL): Boolean = true
}
implicit object FileResource extends Resource[File] {
def content(res: File): String = {
Source.fromFile(res).getLines.mkString("\n")
}
def children(res: File): List[File] = {
if (!hasChildren(res)) List()
else {
res.listFiles().toList
}
}
def hasChildren(res: File): Boolean = res.isDirectory()
}
}
object App {
def countChildren[R: Resource](res: R): Int = {
val resource = implicitly[Resource[R]]
resource.children(res).size
}
def main(args: Array[String]) {
val url = new URL("http://www.typesafe.org/")
val file = new File(".")
println(file.getCanonicalPath())
val counts = (getCountOfChildren(url), getCountOfChildren(file))
println(counts._1, counts._2)
println("Count: " + countChildren(file))
}
def getCountOfChildren[A](obj: A)(implicit resource: Resource[A]) = {
resource.children(obj).size
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.