Scala:如何找出StringOps.map使用哪个CanBuildFrom实现

时间:2015-06-08 07:51:09

标签: string scala mapreduce implicit-conversion builder

我正在通过“Scala for the Impatient”一书中的练习来学习Scala。一个问题是:

  

"abc".map(_.toUpper)的结果是String,但结果是"abc".map(_.toInt)   VectorCanBuildFrom。找出原因。

阅读“The Architecture of Scala Collections”后,我认为这是因为选择了不同的 struct card { int value; char suit; } 隐式实现。我怎样才能找出为上述表达式选择哪些?

1 个答案:

答案 0 :(得分:8)

您可以使用scala> import scala.reflect.runtime.{universe => ru} import scala.reflect.runtime.{universe=>ru} scala> ru.show{ ru.reify{ "abc".map(_.toUpper) }.tree } res0: String = Predef.augmentString("abc").map(((x$1) => Predef.charWrapper(x$1).toUpper))(Predef.StringCanBuildFrom) scala> ru.show{ ru.reify{ "123".map(_.toInt) }.tree } res1: String = Predef.augmentString("123").map(((x$1) => x$1.toInt))(Predef.fallbackStringCanBuildFrom) 来获取所有隐含的内容:

Predef.StringCanBuildFrom

所以CanBuildFrom[String,Char,String] _.toUpper用于Predef.fallbackStringCanBuildFrom,而CanBuildFrom[String,Int,IndexedSeq[Int]] _.toInt用于scala> Predef.StringCanBuildFrom res2: scala.collection.generic.CanBuildFrom[String,Char,String] = scala.Predef$$anon$3@43b7a6fa scala> Predef.fallbackStringCanBuildFrom[Int] res3: scala.collection.generic.CanBuildFrom[String,Int,scala.collection.immutable.IndexedSeq[Int]] = scala.LowPriorityImplicits$$anon$4@61af1aa0

Vector

请注意,类型不是IndexedSeq,而是Vector@MappedSuperclass public abstract class BaseEntity { @Id @GeneratedValue(strategy=GenerationType.SEQUENCE) private Long id; private boolean deleted; @Convert(converter = LocalDateTimePersistenceConverter.class) private LocalDateTime createdAt; @Convert(converter = LocalDateTimePersistenceConverter.class) private LocalDateTime updatedAt; } 是具体实施。