public
Created

  • Download Gist
typedclass.scala
Scala
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
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
}
 
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.