为什么在Kotlin中没有val/var修饰符的主构造函数中需要一个参数? [英] Why do I need a parameter in a primary constructor without val/var modifier in Kotlin?

查看:137
本文介绍了为什么在Kotlin中没有val/var修饰符的主构造函数中需要一个参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我创建一个类,则可以传递一个参数:

If I create a class, I can pass a parameter:

class Person(name: String) {
}

我也可以编写相同的内容,但是使用val时,当我创建对象时,我将能够使用属性来获取该值.

I also can write the same, but with val and then I'll be able to use properties to get this value, when I created an object.

val person = Person("Name")
person.name

问题是:为什么我只需要一个不带val的参数?我应该在哪里,如何以及为什么使用它?

The question is: why do I need just a parameter without the val? Where, how and why should I use it?

推荐答案

如果在构造函数中使用varval,则将声明属性并直接对其进行初始化.如果不这样做,那么这些参数将用于初始化目的:

If you use varor val in the constructor, you are declaring properties and initializing them directly. If you don't, those parameters are used for initialization purposes:

class Customer(name: String) {
    val customerKey = name.toUpperCase()
}

这篇关于为什么在Kotlin中没有val/var修饰符的主构造函数中需要一个参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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