private trait that adds public methods

67 views
Skip to first unread message

Koert Kuipers

unread,
Oct 9, 2016, 5:44:27 PM10/9/16
to scala-user
i often have the need to factor out a few (possibly public) methods between classes in the same package.

i would like to use a trait to factor them out, but i do not want this to be visible. from the public api & scaladoc perspective i basically do not want this trait to exist.

is this possible?

Kevin Wright

unread,
Oct 9, 2016, 6:19:58 PM10/9/16
to Koert Kuipers, scala-user
Yes… but not as a trait.

What you describe doesn’t affect the public interface of the class, and doesn’t take part in polymorphism, so you tick exactly none of the boxes that would normally justify the use of inheritance.  Inheritance is an extremely strong and tightly-coupled mechanism which should only be used sparingly and in limited use-cases.  Anywhere else, composition is a far far better choice!

So. Move the methods into a fully-fledged class, create a private instance of this in your original class, then wildcard-import the methods from there.  Alternatively (if the helper class needs no params), you should instead move the methods into a singleton object and wildcard-import from that.





--
You received this message because you are subscribed to the Google Groups "scala-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email to scala-user+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.



--
Kevin Wright
mail / hangouts / msn : kev.lee...@gmail.com
vibe / skype: kev.lee.wright

"My point today is that, if we wish to count lines of code, we should not regard them as "lines produced" but as "lines spent": the current conventional wisdom is so foolish as to book that count on the wrong side of the ledger" ~ Dijkstra

Koert Kuipers

unread,
Oct 9, 2016, 11:05:10 PM10/9/16
to Kevin Wright, scala-user
hey kevin,
thanks for responding.
the trouble is, the methods i want to factor our are public on these classes. i want to factor them out (why repeat code?), but without the factoring out being visible. so i do not want the scaladoc to be polluted with a mention of the trait/class that i factored them out to.

is this possible?

Stephen Compall

unread,
Nov 12, 2016, 1:42:42 PM11/12/16
to Koert Kuipers, scala-user
On October 9, 2016 11:05:04 PM EDT, Koert Kuipers <ko...@tresata.com> wrote:
>the trouble is, the methods i want to factor our are public on these
>classes. i want to factor them out (why repeat code?), but without the
>factoring out being visible. so i do not want the scaladoc to be
>polluted
>with a mention of the trait/class that i factored them out to.
>
>is this possible?

No, it's not possible. You can hide where implementations come from with enough ceremony, but not interfaces/signatures.

--
Stephen Compall
If anyone in the MSA is online, you should watch this flythrough.
Reply all
Reply to author
Forward
0 new messages