Chinaunix首页 | 论坛 | 博客
  • 博客访问: 3974510
  • 博文数量: 366
  • 博客积分: 9916
  • 博客等级: 中将
  • 技术积分: 7195
  • 用 户 组: 普通用户
  • 注册时间: 2011-05-29 23:27
个人简介

简单!

文章分类

全部博文(366)

文章存档

2013年(51)

2012年(269)

2011年(46)

分类: Java

2012-12-04 21:49:10


  1. package examples

  2. /** Illustrate the use of custom 'apply/update' methods. */
  3. object properties {

  4.   /** A mutable property whose getter and setter may be customized. */
  5.   case class Property[T](init: T) {
  6.     private var value: T = init

  7.     /** The getter function, defaults to identity. */
  8.     private var setter: T => T = identity[T]

  9.     /** The setter function, defaults to identity. */
  10.     private var getter: T => T = identity[T]

  11.     /** Retrive the value held in this property. */
  12.     def apply(): T = getter(value)

  13.     /** Update the value held in this property, through the setter. */
  14.     def update(newValue: T) = value = setter(newValue)

  15.     /** Change the getter. */
  16.     def get(newGetter: T => T) = { getter = newGetter; this }

  17.     /** Change the setter */
  18.     def set(newSetter: T => T) = { setter = newSetter; this }
  19.   }

  20.   class User {
  21.     // Create a property with custom getter and setter
  22.     val firstname = Property("")
  23.       .get { v => v.toUpperCase() }
  24.       .set { v => "Mr. " + v }
  25.     val lastname = Property("")

  26.     /** Scala provides syntactic sugar for calling 'apply'. Simply
  27.      * adding a list of arguments between parenthesis (in this case,
  28.      * an empty list) is translated to a call to 'apply' with those
  29.      * arguments.
  30.      */
  31.     override def toString() = firstname() + " " + lastname()
  32.   }

  33.   def main(args: Array[String]) {
  34.     val user1 = new User

  35.     // Syntactic sugar for 'update': an assignment is translated to a
  36.     // call to method 'update'
  37.     user1.firstname() = "Robert"

  38.     val user2 = new User
  39.     user2.firstname() = "bob"
  40.     user2.lastname() = "KUZ"

  41.     println("user1: " + user1)
  42.     println("user2: " + user2)
  43.   }

  44. }

阅读(1107) | 评论(1) | 转发(0) |
给主人留下些什么吧!~~

txgc_wm2012-12-04 21:51:08

i thought the code is useful,so i copy it here!