6

Scala has the StringLike trait. Let's say I want to create a case class Name and internally it should save the name with some characters. Should I use case class Name(name: StringLike) or case class Name(name: String)?

The former is obviously more abstract. It means someone can give me CustomString that extends StringLike and he might overwrite some methods.

If I want to be sure the given argument behaves like the String class I know, I should use String and else StringLike. Is that correct? Are there cases in which it would make a practically difference?

Also, are there things I can do with the more specialized String that I can't do with a StringLike?

asked Jun 18, 2015 at 15:02

1 Answer 1

8

Although it's usually good practice to accept as abstract of arguments as possible, in Scala you generally want to avoid directly using any types with [Repr] parameters. They are mostly there for the convenience of the standard library implementors.

That's especially true for StringLike, which is primarily intended to augment a Java String to be able to also act like a collection of characters. You're not supposed to look at the man behind the curtain to see how that's accomplished. Nor is it expected that anyone would ever make a custom StringLike implementation.

String is also much better from a simple readability standpoint. If you need something that behaves like a String, just use a String. In the extremely remote chance you ever need something kind of like a String, but not really, you can make the change then, and there may be a better solution.

answered Jun 18, 2015 at 18:34

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.