简体   繁体   中英

What is the default “type” of parameters in scala? Is it Val?

I have a simple class like this.

I haven't specified whether the parameters are val's or var's. What type of parameters are name and price ?

 class Car(name:String, price:Float){ 
 }

The accepted answer is right in principle. In practice, however, if the passed parameter is used in the implementation of a def , it will become an instance field, acting pretty much as if declared using private val (except that no private def getter will be generated for it).

For example:

class Foo(bar: Bar) {
    def foo: Bar = bar
}

can be decompiled into the following java translation (using javap )

public class Foo {
  private final Bar bar;
  public Bar foo();
  public Foo(Bar);
}

See also my answer on this thread for more details about this.

If you declare a class parameter as either var or val , it will become an instance variable. If you don't specify either, it won't. So it's not equivalent to either val or var .

In terms of whether or not they can be re-assigned, class parameters act just like normal parameters, which can't be re-assigned.

Adding to the answer by @sepp2k : If you use a case class then the default is val :

 case class Foo(bar: Bat)

in this case bar is a val that is of public accessibility.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM