Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String viewed as a Sequence

Tags:

In Daniel's answer from this post: What are Scala context and view bounds?

is presented a way of handling a String as a Scala Collection.

handling String and Array, which are Java classes, like they were Scala >collections. For example:

def f[CC <% Traversable[_]](a: CC, b: CC): CC = if (a.size < b.size) a else b

I would like to know where I can find this functionality in the Scala standard libs.

Another easy question related to the post above:

I keep seeing the shorthand "ev" used, especially when related to context bounds or view bounds examples:

def g[A](a: A)(implicit ev: B[A]) = h(a)

What does it stand for?

Thank you in advance. Cheers

like image 591
Adrian Avatar asked Jan 10 '17 13:01

Adrian


1 Answers

I would like to know were I can find this functionality in the Scala standard libs.

Scala provides a wrapper around java.lang.String called WrappedString:

final class WrappedString(val self: String) extends AbstractSeq[Char]
                                            with IndexedSeq[Char] 
                                            with StringLike[WrappedString]

When you run:

f("he", "hello")

The compiler implicitly converts the string literal to an instance of WrappedString via Predef.wrapString:

f[String]("he", "hello")({
  ((s: String) => scala.this.Predef.wrapString(s))
});

In turn, WrappedString extends IndexedSeq[Char], and that is why it obeys the view bounds request to be convertible to a traversable.

I keep seeing the shorthand "ev" used, especially when related to context bounds or view bounds, what does it stand for?

It's short for "evidence". If you think about it, when you request some kind of implicit parameter to be in scope the compiler is requiring you to provide evidence that the operation can happen.

like image 173
Yuval Itzchakov Avatar answered Sep 23 '22 09:09

Yuval Itzchakov