I did experiment on CanBuildFrom trait on Scala, it looks fine when I try to convert Array type to Seq type automatically, I think the reason is that we have CanBuildFrom[Array, T, Seq[T]] in the scope. However, if I try to convert Array to Set, it is not working. Further, Converting Seq to Set is not working as well. I just wonder should I define implicit into same type CanBuildFrom companion object to implement conversion ?. If it is, why scala doesnt provide it by default, is reason Set is a function ?
Here is the code which for Array to Seq
def transform[U[_]](col: Array[String])(implicit cbf: CanBuildFrom[Array[String], String, U[String]]): U[String] = {
val builder = cbf()
for (ele <- col) builder += ele
builder.result()
}
CanBuildFromSpec.transform[Seq](Array("123", "3"))
If I want to convert to Array to Set or List, it is not working
CanBuildFromSpec.transform[List](Array("123", "3")) //compilation error, cannot construct
CanBuildFromSpec.transform[Set](Array("123", "3")) //compilation error, cannot construct
collection.breakOut
as theCanBuildFrom
to yourtransform
to allow you to build any collection (any that can holds strings at least). Or you can declare an implicitCanBuildFrom
of the needed type. – wingedsubmariner