Advertisement
Guest User

Untitled

a guest
Aug 5th, 2015
176
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.87 KB | None | 0 0
  1. import java.util.Date
  2. import org.joda.time.format.DateTimeFormat
  3.  
  4. // 暗黙のクラス
  5.  
  6. class Sample1 {
  7.  
  8. def sample = {
  9. "Gunma".hello // => Hello, Gunma
  10. }
  11.  
  12. implicit class HelloString(string: String) {
  13.  
  14. def hello = {
  15. "Hello, " + string
  16. }
  17.  
  18. }
  19.  
  20. }
  21.  
  22. // 暗黙の型変換
  23.  
  24. class Sample2 {
  25.  
  26. def time(date: Date) = {
  27. date.getTime
  28. }
  29.  
  30. def sample = {
  31. time(new Date())
  32. time("2015/07/18")
  33. }
  34.  
  35. implicit def string2date(dateString: String): Date = {
  36. val formatter = DateTimeFormat.forPattern("yyyy/MM/dd")
  37. formatter.parseDateTime(dateString).toDate
  38. }
  39.  
  40. }
  41.  
  42. // 暗黙の引数
  43.  
  44. class Greet {
  45.  
  46. def hello(implicit name: String) = {
  47. "Hello, " + name
  48. }
  49.  
  50. }
  51.  
  52. class Sample3 {
  53.  
  54. implicit val name = "Gunma"
  55.  
  56. def sample = {
  57. val greet = new Greet
  58. greet.hello("World") // => Hello, World
  59. greet.hello // => Hello, Gunma
  60. }
  61.  
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement