返回顶部

收藏

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. Harries 发表 2018-10-16 12:22:30 从Scala(2.10)类型的标签或符号获取Java类的任何方法?
  2. 博主 发表 2016-12-31 04:38:37 hadoop流水账之HBase,Spark和在Spark上操作HBase
  3. 博主 发表 2016-12-31 04:38:37 Java/Scala杂记之一
  4. 博主 发表 2016-12-31 04:38:37 Java/Scala杂记之二
  5. 博主 发表 2016-12-31 04:38:37 Java/Scala杂记之三
  6. 博主 发表 2016-12-31 04:38:37 Java/Scala杂记之三
  7. 博主 发表 2017-01-07 07:34:01 一年一语言之2016
  8. xiaoli.wang 发表 2018-09-10 13:30:56 穷人创业指南,告诉你没钱该如何创业?
  9. 炒饭 发表 2015-06-13 08:32:43 Scala学习(一)——类、对象和变量
  10. 炒饭 发表 2015-06-16 15:48:52 Scala学习(二)——成员,方法和构造方法
  11. 炒饭 发表 2015-06-18 07:42:29 Scala学习(三)——代码块和流程控制
  12. 炒饭 发表 2015-06-18 14:44:34 Scala学习(四)——类型

发表评论