In scala is it possible for a trait to extend a class which needs parameters?
Asked Answered
M

2

11

I know a trait can extend a class which has an empty parameter constructor:

class Foo
trait Bar extends Foo

but is it possible to extend a class which constructor has some parameters?

class Foo(b: Boolean)
trait Bar extends Foo(true)

Is it possible to achieve this? It seems it's not possible. but why?

Thanks

Massasauga answered 21/8, 2015 at 5:15 Comment(0)
A
4

Yes, it's possible, you just can't give constructor arguments:

trait Bar extends Foo { ... }

But to instantiate it you need to call the constructor as well:

new Foo(false) with Bar
Adeno answered 21/8, 2015 at 7:54 Comment(0)
P
2

Making the arg a val seems to work.

scala> class Foo(val b: Boolean)
defined class Foo

scala> trait Bar extends Foo {override val b = true}
defined trait Bar

This also works if you make the class a case class which automatically turns the args in to vals.

EDIT

As @Aleksey has pointed out, this compiles but it's a trait that can't be instantiated so, no, it still doesn't seem possible. You'll have to make Bar a class.

scala> class Bar extends Foo(false) {println(b)}
defined class Bar

scala> new Bar
false
Psychotechnology answered 21/8, 2015 at 5:48 Comment(1)
can you instantiate it?Smectic

© 2022 - 2024 — McMap. All rights reserved.