Skip to content

Instantly share code, notes, and snippets.

View kmizu's full-sized avatar

Kota Mizushima kmizu

View GitHub Profile
@kmizu
kmizu / package.scala
Created May 21, 2011 16:34
A package object that have case classes and main method.
package object foobar {
case class A
case class B
def main(args: Array[String]) {
println("Hello")
}
}
// scalac package.scala
// scala foobar.package
@kmizu
kmizu / JssonBuilder.scala
Created May 22, 2011 07:16
JSON like Scala object notation
import scala.util.DynamicVariable
object JssonBuilder {
private val status = new DynamicVariable[Map[String, Any]](null)
class ArrowOperatorExtension(key: String) {
//Warning: this could cause unexpected behavior
def ->(value: Any): (String, Any) = {
val result = (key, value)
status.value = status.value + result
result
}
scala> {
| import scala.io._
| val r = Source.fromFile("file.txt")
| println(r.getLines().toList)
| }
@kmizu
kmizu / A.scala
Created May 25, 2011 16:37
overloading in package object
import foo._
object A {
def main(args: Array[String]) {
println(plus(1))
println(plus(1, 3))
}
}
//scalac package.scala
//scalac A.scala
//scala A
@kmizu
kmizu / Magic.scala
Created June 24, 2011 21:48
Usage of ClassManifest
def matchType[A:ClassManifest](value: Any): Boolean = {
val classAny: Class[_] = value match {
case _:Byte=> classOf[Byte]
case _:Short => classOf[Short]
case _:Int => classOf[Int]
case _:Long => classOf[Long]
case _:Float => classOf[Float]
case _:Double => classOf[Double]
case _:Char => classOf[Char]
case _:Boolean => classOf[Boolean]
@kmizu
kmizu / ByNameParams.scala
Created June 25, 2011 08:43
Experiments about by-name parameter in Scala
class ByNameParams {
private def multiply(x: => Int) : Int = x * 2
def hello {
multiply(100)
}
}
@kmizu
kmizu / GrepUsage.scala
Created July 1, 2011 22:16
Add grep method to any collection that holds String.
scala> import PimpGrepToCollection._
import PimpGrepToCollection._
scala> List("123", "156", "C").grep("\\d"){_.toInt}
res0: List[Int] = List(123, 156)
scala> Set("123", "456", "XXX").grep("\\d"){_.toInt}
res1: scala.collection.immutable.Set[Int] = Set(123, 456)
scala> Vector("A", "100", "XXX").grep("\\d"){_.toInt}
@kmizu
kmizu / ImplicitRecursion.scala
Created July 2, 2011 11:26
An implicit conversion that itself requires another implicit conversion.
object ImplicitRecursion {
abstract class Nat
class Zero extends Nat
class Succ[T <: Nat] extends Nat
type _0 = Zero
type _1 = Succ[_0]
type _2 = Succ[_1]
type _3 = Succ[_2]
type _4 = Succ[_3]
type _5 = Succ[_4]
@kmizu
kmizu / Bean.scala
Created July 8, 2011 15:29
An example of @BeanProperty annotation.
import scala.reflect.BeanProperty
trait Bean {
@BeanProperty var x: Int
}
class BeanImpl(@BeanProperty var x: Int) extends Bean
@kmizu
kmizu / Foo.scala
Created July 10, 2011 07:36
A case that "private" method of Scala is compiled into "public" method of class file.
class Foo {
private def foo {
Foo.foo
}
}
object Foo {
private def foo {
println("foo")
}
}