Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use method return value as default constructor parameter in Scala

Tags:

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?

like image 739
bwroga Avatar asked Mar 31 '26 15:03

bwroga


2 Answers

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

class foo (baz: Array[Int] = foo.bar) {
}
like image 73
missingfaktor Avatar answered Apr 02 '26 14:04

missingfaktor


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)
}
like image 36
pagoda_5b Avatar answered Apr 02 '26 13:04

pagoda_5b



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!