Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement