0

Experimenting with map, flatMap and flatten and the following output is unexpected :

  case class T(data: String)
  val s = Set(T("1") , T("2"))
  val a: Array[Byte] = s.map(transaction => transaction.data).flatten.toArray

Should a not be of type Array[String]? , as data is of type String. Why is a of type Array[Byte]?

1 Answer 1

3

The call to flatten is happening on a Set[String]. The String is treated something like an Iterable[Byte] (since that's more or less what a string is). So the flatten call is effecitively taking a Set[Iterable[Byte]] and flattening it into a Set[Byte] (which you then convert to an Array[Byte]).

Drop the flatten call and you'll get what you're after.

https://scastie.scala-lang.org/GqQiOHiWSZ6GKwdoM41yAg

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.