Skip to content

Instantly share code, notes, and snippets.

@honda0510
Created July 19, 2015 01:26
Show Gist options
  • Save honda0510/80feab67a5f8463d099e to your computer and use it in GitHub Desktop.
Save honda0510/80feab67a5f8463d099e to your computer and use it in GitHub Desktop.
implicit programming
import java.util.Date
import org.joda.time.format.DateTimeFormat
// 暗黙のクラス
class Sample1 {
def sample = {
"Gunma".hello // => Hello, Gunma
}
implicit class HelloString(string: String) {
def hello = {
"Hello, " + string
}
}
}
// 暗黙の型変換
class Sample2 {
def time(date: Date) = {
date.getTime
}
def sample = {
time(new Date())
time("2015/07/18")
}
implicit def string2date(dateString: String): Date = {
val formatter = DateTimeFormat.forPattern("yyyy/MM/dd")
formatter.parseDateTime(dateString).toDate
}
}
// 暗黙の引数
class Greet {
def hello(implicit name: String) = {
"Hello, " + name
}
}
class Sample3 {
implicit val name = "Gunma"
def sample = {
val greet = new Greet
greet.hello("World") // => Hello, World
greet.hello // => Hello, Gunma
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment