Skip to content

Instantly share code, notes, and snippets.

@itang
Created February 19, 2021 17:33
Show Gist options
  • Save itang/efdfcfdb88e9c0e398ed4275e7b37ccd to your computer and use it in GitHub Desktop.
Save itang/efdfcfdb88e9c0e398ed4275e7b37ccd to your computer and use it in GitHub Desktop.
import java.util.{Date as JDate}
import scala.io.Source as S
trait JsonOps[T] {
def stringify(t: T): String
extension (x:T) def toJSON(): String = stringify(x)
}
given intJsonOps: JsonOps[Int] with {
override def stringify(t: Int): String = t.toString
}
given stringJsonOps: JsonOps[String] with {
override def stringify(t: String): String = "\"" + t + "\""
}
given listJsonOps[T](using j: JsonOps[T]): JsonOps[List[T]] with {
override def stringify(t: List[T]): String = {
val s = StringBuilder()
s.append("[")
t.foreach(it => s.append(j.stringify(it)).append(","))
s.append("]")
s.toString
}
}
def toJson[T](t: T)(using j: JsonOps[T]) = j.stringify(t)
object A {
extension[T] (t: T)
def toJson()(using j: JsonOps[T]): String = j.stringify(t)
}
trait X[T]{
extension (t:T) def x(): String
}
given intX: X[Int] with {
extension (t: Int) def x(): String = t.toString()
}
object Main {
def main(args: Array[String]): Unit = {
println("Hello world!")
println(msg)
val s = S.fromFile("build.sbt").getLines().mkString(",\n")
//println(s)
println(JDate())
println(toJson(100))
println(toJson("200"))
println(toJson(List(1, 2, 3)))
println(toJson(List("a", "b", "c")))
println(List(1, 2, 3).toJSON())
{
import A.*
println("hello".toJson())
println(List("e", "f").toJson())
}
{
import intX.*
println(100000.x())
}
}
def msg = "I was compiled by dotty :)"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment