在 scala 中使用 def、val 和 var [英] Use of def, val, and var in scala

查看:50
本文介绍了在 scala 中使用 def、val 和 var的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class Person(val name:String,var age:Int )
def person = new Person("Kumar",12)
person.age = 20
println(person.age)

这些代码行输出 12,即使 person.age=20 已成功执行.我发现这是因为我在 def person = new Person("Kumar",12) 中使用了 def.如果我使用 var 或 val,则输出为 20.我知道默认值是 val 在 Scala 中.这:

These lines of code outputs 12, even though person.age=20 was successfully executed. I found that this happens because I used def in def person = new Person("Kumar",12). If I use var or val the output is 20. I understand the default is val in scala. This:

def age = 30
age = 45

...给出一个编译错误,因为它默认是一个 val.为什么上面的第一组行不能正常工作,但也不出错?

...gives a compilation error because it is a val by default. Why do the first set of lines above not work properly, and yet also don't error?

推荐答案

在 Scala 中有三种定义事物的方式:

There are three ways of defining things in Scala:

  • def 定义了一个方法
  • val 定义了一个固定的(不能修改)
  • var 定义了一个变量(可以修改)
  • def defines a method
  • val defines a fixed value (which cannot be modified)
  • var defines a variable (which can be modified)

查看您的代码:

def person = new Person("Kumar",12)

这定义了一个名为 person 的新方法.您只能在没有 () 的情况下调用此方法,因为它被定义为无参数方法.对于空括号方法,您可以使用或不使用 '()' 调用它.如果你只是写:

This defines a new method called person. You can call this method only without () because it is defined as parameterless method. For empty-paren method, you can call it with or without '()'. If you simply write:

person

然后您正在调用此方法(如果您不分配返回值,它将被丢弃).在这行代码中:

then you are calling this method (and if you don't assign the return value, it will just be discarded). In this line of code:

person.age = 20

发生的事情是您首先调用 person 方法,然后在返回值(Person 类的实例)上更改 age 成员变量.

what happens is that you first call the person method, and on the return value (an instance of class Person) you are changing the age member variable.

最后一行:

println(person.age)

这里再次调用 person 方法,该方法返回 Person 类的新实例(age 设置为 12).和这个一样:

Here you are again calling the person method, which returns a new instance of class Person (with age set to 12). It's the same as this:

println(person().age)

这篇关于在 scala 中使用 def、val 和 var的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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