bwroga
bwroga

Reputation: 5459

Use method return value as default constructor parameter in Scala

This is what I would like to do:

object foo {
    def bar = Array(1, 2, 3, 4, 5)
}
class foo (baz = bar) {
}

This causes compiler errors. Is there another way to accomplish this?

Upvotes: 2

Views: 471

Answers (3)

Jens Schauder
Jens Schauder

Reputation: 81882

you can write a secondary constructor:

object foo {
    def bar = Array(1, 2, 3, 4, 5)
}

class foo (baz : Array[Int]) {
    def this(){
        this(bar)
    }
}

Written without IDE or compiler, so someone has to fix the typos.

Upvotes: 1

pagoda_5b
pagoda_5b

Reputation: 7373

You can use an auxiliary constructor

object Foo {
  def bar = Array(1, 2, 3, 4, 5)
}

class Foo(baz: Array[Int]) {
  def this() = this(Foo.bar)
}

Upvotes: 1

missingfaktor
missingfaktor

Reputation: 92026

object foo {
    def bar = Array(1, 2, 3, 4, 5)
}

class foo (baz: Array[Int] = foo.bar) {
}

Upvotes: 12

Related Questions