Frage

Why output is -10?

class Person {
        var age: Int = 0
        def age_(newAge: Int) {
                if( newAge > 0 ) age = newAge
        }
}

object Main extends App {
        val p = new Person
        p.age = -10
        println(p.age)
}

scalac Main.scala
scala Main
-10

War es hilfreich?

Lösung

You probably wanted to write setter but due to the wrong syntax you ended up with a variable visible from the outside AND weirdly named method:

val x = new Person()
x.age_(3)
x.age_(-10)

x.age
//  Int = 3

Correct way of writing setter could be (note trailing = in the method name):

class Person {
    private var privateAge: Int = 0

    def age_=(newAge: Int) {
      if( newAge > 0 ) privateAge = newAge
    }

    def age = privateAge
}

val x = new Person()
x: Person = Person@42c08a7e

x.age = -10
// x.age: Int = 0

x.age
// res7: Int = 0

Andere Tipps

val p = new Person
p.age = -10

You are setting the age value to -10

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top