gpt4 book ai didi

scala - 方法名称中的下划线

转载 作者:行者123 更新时间:2023-12-03 23:15:12 28 4
gpt4 key购买 nike

各位斯卡拉主义者,大家好,

我最近再次查看了 Scala 中的 setter,发现方法名称中的 _ 似乎转换为“可能有空格或没有,哦,也将下一个特殊字符视为方法名称的一部分”。

  • 所以首先,这是正确的吗?
  • 其次,有人可以解释为什么倒数第二行不起作用吗?
    class Person() {
    private var _name: String = "Hans"
    def name = _name
    def name_=(aName: String) = _name = aName.toUpperCase
    }
    val myP = new Person()
    myP.name = "test"
    myP.name= "test"
    myP.name_= "test" //Bad doesnt work
    myP.name_=("test")//Now It works
  • 最后,删除 getter 打破了上面的例子
    class Person() {
    private var _name: String = "Hans"
    def name_=(aName: String) = _name = aName.toUpperCase
    }
    val myP = new Person()
    myP.name = "test" //Doesnt work anymore
    myP.name= "test" //Doesnt work anymore
    myP.name_= "test" //Still doesnt work
    myP.name_=("test")//Still works

  • 编辑:
    这是我最初阅读的来源的引用(看似错误),并产生了这个问题:

    This line is a bit more tricky but I'll explain. First, the method name is "age_=". The underscore is a special character in Scala and in this case, allows for a space in the method name which essentially makes the name "age ="



    http://dustinmartin.net/getters-and-setters-in-scala/

    最佳答案

    So first of all, is this correct?



    不,方法名称中的下划线与您描述的不完全一样。这并不意味着“可能有一个空格,空格后面的字符也是方法名称的一部分”。

    Section 4.2 Scala Language Specification 解释了名称以 _= 结尾的方法。方法。

    A variable declaration var x: T is equivalent to the declarations of both a getter function x and a setter function x_=:

    def x: T
    def x_= (y: T): Unit

    An implementation of a class may define a declared variable using a variable definition, or by defining the corresponding setter and getter methods.



    请注意,如果您只定义了 setter 方法而不定义了 getter 方法,那么 setter 方法的魔力就会消失——它被视为另一个名称恰好以 _= 结尾的方法。 ,但这在这种情况下没有特殊意义。

    只有当有getter和setter时,方法才 _=充当 setter 并且可以这样使用 - 这就是为什么 myP.name = "test"如果您删除 setter/getter ,则不再起作用。

    关于scala - 方法名称中的下划线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34470980/

    28 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com