返回顶部

收藏

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. 博主 发表 2018-05-10 01:28:07 理解本真的AKKA架构风格
  2. 博主 发表 2018-05-10 07:15:24 使用nexus发布和获取依赖包
  3. robin 发表 2018-04-21 01:49:49 使用Gradle构建scala多模块工程
  4. 博主 发表 2018-04-18 12:58:39 发布Scala构件至Maven中央库
  5. 博主 发表 2017-11-30 02:42:43 Scala调用Matlab(MCR)进行数据拟合并获取结果
  6. 博主 发表 2017-10-22 06:36:12 Scala的正确打开姿势--搭建开发环境
  7. 博主 发表 2017-10-16 15:01:58 AWS 上 Kylin 调度系统的设计
  8. Josh Long 发表 2017-10-11 00:40:00 Spring Tips: Bootiful, Reactive Scala
  9. Anyone (hang.yan@hot 发表 2015-08-30 16:00:00 Scala笔记: 函数和闭包
  10. 博主 发表 2017-07-22 02:18:26 scala的for循环yield值
  11. 博主 发表 2017-07-22 02:18:26 spark 隐含因子音乐推荐
  12. 博主 发表 2017-07-22 02:18:26 spark rdd 转换和动作

发表评论