使用自定义_ =的Scala自动getter和setter覆盖 [英] Scala automatic getter and setter overwriting with custom _=

查看:267
本文介绍了使用自定义_ =的Scala自动getter和setter覆盖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在scala中,类的用户在调用方法或直接使用val x = myclass.myproperty访问某些字段/成员之间没有区别.为了能够控制例如设置或获取字段时,scala让我们覆盖_ =方法.但是=真的是一种方法吗?我很困惑.

In scala there is no difference for the user of a class between calling a method or accessing some field/member directly using val x = myclass.myproperty. To be able to control e.g. setting or getting a field, scala let us override the _= method. But is = really a method? I am confused.

让我们采用以下代码:

class Car(var miles: Int)

var myCar = new Car(10)
println(myCar.miles) //prints 10
myCar.miles = 50
println(myCar.miles) //prints 50

此代码也一样(请注意myCar.miles = 50中的双倍空格):

Same goes for this code (notice the double space in myCar.miles = 50):

class Car(var miles: Int)

var myCar = new Car(10)
println(myCar.miles) //prints 10
myCar.miles  = 50
println(myCar.miles) //still prints 50

现在我想更改miles的设置或读取方式,例如总是在屏幕上打印一些东西.如何做到这一点,以使班级的用户不受影响,并且如果在=号之前使用空格,也不会造成任何影响?

Now i want to change the way how the miles can be set or read, e.g. always printing something on the screen. How can i do this so that the users of my class are not affected and also so that it does not make any difference if whitespaces are used before the = sign?

推荐答案

尝试一下:

class Car(private var _miles: Int) {
  def miles = _miles
  def miles_=(m: Int): Unit = {
    println("boo")
    _miles = m
  }
}

空格不重要.编译器会看到您正在分配miles,并且无论您插入多少空格,都将插入对miles_=的调用.

Whitespace is not significant. The compiler sees you're assigning miles and will insert a call to miles_= no matter how many spaces you insert.

这篇关于使用自定义_ =的Scala自动getter和setter覆盖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆