0

I know that one can use a companion ojbect to declare static variables and functions for a Class in Scala, but is there a way to do declare static variables/funcions in a Trait?

1
  • No, you can't. Specially because Scala does not really has the concept of static, it only has values. Now, we all know that objects are compiled down to static fields, but that is just a runtime detail. - If you want something to be created only one time, you would need to define it on an object. On your trait you can have a reference to that val on that object if you want. Commented Jul 31, 2019 at 21:43

1 Answer 1

1

You can have a companion object for a trait in the same way that you have a companion object for a class.

So you can't declare static values inside the trait because Scala does not work that way, but you can achieve the same thing using the companion object.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.