返回顶部

收藏

Scala 之 Properties

更多

properties.scala

package examples

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

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

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

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

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

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

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

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

  class User {
    // Create a property with custom getter and setter
    val firstname = Property("")
      .get { v => v.toUpperCase() }
      .set { v => "Mr. " + v }
    val lastname = Property("<noname>")

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

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

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

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

    println("user1: " + user1)
    println("user2: " + user2)
  }

}

标签:scala

收藏

0人收藏

支持

0

反对

0

相关聚客文章
  1. 炒饭 发表 2015-06-13 08:32:43 Scala学习(一)——类、对象和变量
  2. 炒饭 发表 2015-06-16 15:48:52 Scala学习(二)——成员,方法和构造方法
  3. 炒饭 发表 2015-06-18 07:42:29 Scala学习(三)——代码块和流程控制
  4. 炒饭 发表 2015-06-18 14:44:34 Scala学习(四)——类型
  5. 炒饭 发表 2015-06-21 14:32:53 Scala学习(五)——泛型
  6. 炒饭 发表 2015-06-25 04:59:54 Scala学习(六)——运算符
  7. 炒饭 发表 2015-06-27 14:55:39 Scala学习(七)——Apply和Unapply
  8. 炒饭 发表 2015-07-01 13:19:08 Scala学习(杂1)
  9. 炒饭 发表 2015-07-03 14:12:45 Scala学习(八)——异常处理
  10. 炒饭 发表 2015-07-12 08:14:40 Scala学习(九)——隐式转换
  11. 炒饭 发表 2015-09-02 01:44:53 Scala学习(十)——作用域和import
  12. 炒饭 发表 2015-09-30 03:30:38 Scala学习(十一)——lambda表达式

发表评论