This page is no longer maintained — Please continue to the home page at www.scala-lang.org

Constructors in Scala

2 replies
staar2
Joined: 2009-02-28,
User offline. Last seen 42 years 45 weeks ago.

I am new with Scala, as I am reading book "Programming in Scala", I got
question. In Scala we have class parameters. But what if i would like to
declare more then one constructor with different parameter types ?

staar2
Joined: 2009-02-28,
User offline. Last seen 42 years 45 weeks ago.
Re: Constructors in Scala

staar2 wrote:
>
> I am new with Scala, as I am reading book "Programming in Scala", I got
> question. In Scala we have class parameters. But what if i would like to
> declare more then one constructor with different parameter types ?
>
Ok, i got myself answer. You can use auxiliary constructors, if your
defining an auxilary constructor you need to use the primary constructor.

Tony Morris
Joined: 2008-12-19,
User offline. Last seen 30 weeks 4 days ago.
Re: Constructors in Scala

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Hi,
Does this snippet from the Scala REPL help?

scala> class C(i: Int, s: String) { def this(n: Int) = this(n, "boo!") }
defined class C

scala> val x = new C(7)
x: C = C@2598a35d

scala> val y = new C(7, "blah!")
y: C = C@7844a013

staar2 wrote:
> I am new with Scala, as I am reading book "Programming in Scala", I got
> question. In Scala we have class parameters. But what if i would like to
> declare more then one constructor with different parameter types ?

- --
Tony Morris
http://tmorris.net/

S, K and I ought to be enough for anybody.

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.9 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iEYEARECAAYFAkmpFaMACgkQmnpgrYe6r63DYACfRWY8CHOwInQ4DPLjz3kyPoXJ
/KYAoLbGqOs0Nd26S11xUMpApTNqNnmc
=Swkn
-----END PGP SIGNATURE-----

Copyright © 2012 École Polytechnique Fédérale de Lausanne (EPFL), Lausanne, Switzerland