Scala 隐式转换:将 Int 转换为 List 在打印整数变量时不打印列表

Scala implicit conversion: converting Int to List does not print list on printing the integer variable

我正在试验 scala 的隐式转换功能。

我试着写了一个从 Int 隐式转换为三个相同整数的 List 的方法

虽然列表方法是适用的,但是当我们打印值时它仍然显示为整数

scala> implicit def conversion(x:Int) = List(x,x,x)
conversion: (x: Int)List[Int]

scala> 1
res31: Int = 1

scala> res31.length
res32: Int = 3

scala> res31.tail
res33: List[Int] = List(1, 1)

scala> println(res31)
1

知道为什么会出现这种行为吗?理想情况下,它应该打印如下:

List(1, 1, 1)

隐式转换仅在无法应用原始值时才会启动,例如没有带有此类参数的方法。因为您可以打印 Int ,所以 Scala 有 "no need" 来应用转换。你可以强制它: println(res31:List[Int])

查看文档:http://docs.scala-lang.org/tutorials/tour/implicit-conversions.html

Implicit conversions are applied in two situations:

If an expression e is of type S, and S does not conform to the expression’s expected type T. In a selection e.m with e of type S, if the selector m does not denote a member of S.

所以对于你的例子,除了res31.tail,没有type conversion发生,在res31.tail需要调用List类型的tail方法,这个动作触发 implicit 转换。其他操作不会触发 隐式转换

要打印成您可以使用的列表, println(res53.toList)

println 期望类型为 Any 的参数,因此不需要隐式转换。在前两种情况下,Int 没有名为 lengthtail 的方法,但 List 有它们,这就是在这些表达式中进行转换的原因。