Created
July 19, 2015 01:26
-
-
Save honda0510/80feab67a5f8463d099e to your computer and use it in GitHub Desktop.
implicit programming
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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