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?

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.