Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using scala constructor to set variable defined in trait

If I understand correctly, traits are the closest thing to Java interfaces and class constructors automatically set the variables.

But what if I have a class that extends a trait and has a constructor which sets a variable from the trait, so something like:

trait Foo {     var foo: String }  class Bar (foo: String) extends Foo { /* ... */ } 

Where I want the foo string of the trait been set when I make a Bar object.

The compiler seems to give me errors about this. What is the correct way to achieve this?

like image 553
Seba Kerckhof Avatar asked Nov 18 '11 06:11

Seba Kerckhof


People also ask

Can Scala trait have constructor?

Traits does not contain constructor parameters. When a class inherits one trait, then use extends keyword.

Can Scala trait have variables?

In scala, trait is a collection of abstract and non-abstract methods. You can create trait that can have all abstract methods or some abstract and some non-abstract methods. A variable that is declared either by using val or var keyword in a trait get internally implemented in the class that implements the trait.

Can a trait take parameters Scala?

Unlike a class, Scala traits cannot be instantiated and have no arguments or parameters. However, you can inherit (extend) them using classes and objects.

Can we create object of trait in Scala?

Traits are used to define object types by specifying the signature of the supported methods. Scala also allows traits to be partially implemented but traits may not have constructor parameters.


2 Answers

trait Foo { var foo: String = _ } class Bar(foo0: String) extends Foo { foo = foo0 } 

The trait declares an uninitialized var; the class then sets it equal to the input parameter.

Alternatively,

trait Foo {   def foo: String   def foo_=(s: String): Unit } class Bar(var foo: String) extends Foo {} 

declares the getter/setter pair corresponding to a foo, which are set by the class.

like image 50
Rex Kerr Avatar answered Sep 23 '22 19:09

Rex Kerr


Bar must define the abstract var foo in Foo (would be the same for a val). This can be done in the constructor

class Bar(var foo: String) extends Foo{...} 

(of course, it could be done in the body of Bar too). By default, constructor parameters will be turned to private val if need be, that is if they are used outside the initiailization code, in methods. But you can force the behavior by marking them val or var, and possibly control the visibility as in

class X(protected val s: String, private var i: Int) 

Here you need a public var to implement Foo.

like image 28
Didier Dupont Avatar answered Sep 24 '22 19:09

Didier Dupont