看到hackernews上推荐的《scala: the good,the bad and the very ugly》在这篇ppt里,有一个例子挺有意思的:
List(1,2,3).toSet()
猜一下它的结果,直观上我们会认为它返回一个Set类型的集合,实际却不是:
scala> List(1,2,3).toSet()
<console>:8: warning: Adaptation of argument list by inserting () has been deprecated: this is unlikely to be what you want.
signature: GenSetLike.apply(elem: A): Boolean
given arguments: <none>
after adaptation: GenSetLike((): Unit)
List(1,2,3).toSet()
^
res1: Boolean = false
在repl下测试,在给出警告之后,输出了一个Boolean
值。让人大跌眼镜,要想得到预期的结果,方法后边的小括号是不能写的:
scala> List(1,2,3).toSet
res9: scala.collection.immutable.Set[Int] = Set(1, 2, 3)
其实警告信息里已经很明确的说明了,toSet()
实际是对toSet
的结果再调用的GenSetLike.apply(elem: A)
,即它相当于
List(1,2,3).toSet.apply()
如果apply方法是无参的,上面的也好理解,但警告信息里提示的是:GenSetLike.apply(elem: A)
明明时带有一个参数的,为什么用空的参数apply()
也可以运行?
等等,警告信息里还有2句:
given arguments: <none>
after adaptation: GenSetLike((): Unit)
这两句是说给了一个空参数,被编译器适配成了一个Unit类型的()
实例对象,是不是有些匪夷所思?编译器为何要自作聪明?如果我们对Unit类型的谜题还有印象的话,会怀疑是否因为Unit类型用作方法参数引起的:
scala> def foo(u:Unit) { println("ok") }
scala> foo() // 可以运行,同样也会有类似上面的警告信息
参考以前两篇有关Unit的: scala雾中风景(4): Unit类型 和 scala雾中风景(8): 高阶函数与Unit的谜题
不过,这里是否真的就是Unit类型引起的? 虽然警告信息里提示把空参数适配成了Unit类型,但并不是apply方法声明的参数,GenSetLike.apply(elem: A)
参数类型是一个泛型参数,我们先根据直觉判断 List(1,2,3).toSet
之后得到的是Set[Int]
,所以这里A是Int类型?我们一步步来验证一下:
scala> val s = List(1,2,3).toSet
s: scala.collection.immutable.Set[Int] = Set(1, 2, 3)
scala> s.apply() // 错误,提示缺乏参数!用IDE的话发现编译时就提示错误了
诡异了,分成两步的时候居然又不行了,虽然这时的提示更符合预期,但之前用一句表达 List(1,2,3).toSet.apply()
为什么又可以运行?
经过google之后,发现这竟然是一个很有趣的类型推导问题,参考这篇讨论
scala.collection.immutable.Set
是非协变的(实际是invariant的),这点不同于List
,Seq
,Queue
等主流集合的声明。为什么要定义为非协变的,也是由Set自身的函数特征决定的trait Set[A] extends (A => Boolean)
,可以参考这里的解释。
TraversableOnce.toSet
方法声明是:
def toSet[B >: A]: immutable.Set[B] = ...
注意,它返回的类型不同于List[A]里的A,而是A的某个父类型B!这里存在一个很常见的类型推导问题:
scala> List(1,2,3).toSet.map(x=>x+1) // 错误,缺乏参数类型
scala> List(1,2,3).toSet.map((x:Int)=>x+1) // 需要显式声明参数类型
res28: scala.collection.immutable.Set[Int] = Set(2, 3, 4)
scala> List(1,2,3).toSet[Int].map(x=>x+1) // 或在toSet的时候显式的声明元素类型为Int
res29: scala.collection.immutable.Set[Int] = Set(2, 3, 4)
或分两步,先得到set结果,再map不需要显式声明参数类型:
scala> val s = List(1,2,3).toSet // 先得到set结果
s: scala.collection.immutable.Set[Int] = Set(1, 2, 3)
scala> s.map(x=>x+1) // OK
res30: scala.collection.immutable.Set[Int] = Set(2, 3, 4)
为啥分开写,跟连着写在toSet
阶段的类型推导是不一样的呢,typesafe的开发Adriaan Moors给了解释
You can think of inference as a breadth-first sweep over the expression, collecting constraints (which arise from subtype bounds and required implicit arguments) on type variables, followed by solving those constraints. This approach allows, e.g., implicits to guide type inference. In your example, even though there is a single solution if you only look at the xs.toSet subexpression, later chained calls could introduce constraints that make the system unsatisfiable. The downside of leaving the type variables unsolved is that type inference for closures requires the target type to be known, and will thus fail (it needs something concrete to go on — the required type of the closure and the type of its argument types must not both be unknown).
Now, when delaying solving the constraints makes inference fail, we could backtrack, solve all the type variables, and retry, but this is tricky to implement (and probably quite inefficient).
大致是类型推导是广度优先的方式扫描表达式,搜集类型变量上由子类型界定和隐式参数导致的约束,接下来解释这些约束。。。
所以在一整句连着写List(1,2,3).toSet.apply()
的toSet
阶段因为其上下文约束不同于单句的List(1,2,3).toSet
,还未能推导此时Set的元素类型。
我们通过-Ytyper-debug
选项可以看到分开写的时候,类型推导的确是明确推导出结果是Set[Int]
了:
而连在一起写的时候,并未明确推导出Set的元素类型,这里B类型是Int的父类型:
现在,我们了解到了List(1,2,3).toSeq.apply()
在apply()之前因为元素类型还未明确(B是Int的父类型),B可能是一个非常“泛”的类型,比如AnyVal或Any,这样相当于:
scala> val s: Set[Any] = List(1,2,3).toSeq
scala> s.apply() // 给出警告,但运行OK!
现在问题就变成了,为和一个很宽泛的类型比如Any
或AnyRef
,用作参数类型的时候,实际调用这个方法时参数可以随意传递?
scala> def foo(a:Any) { println("ok") }
scala> foo(1,2,3) // 给出警告,但运行OK
scala> foo() // 给出警告,但运行OK
其实这个问题跟之前的这篇 scala雾中风景(16): println(1,2,3)为什么work? 属于同一个问题,scala编译器发觉对只有一个参数的方法在调用时参数不一致的情况下,会在最后阶段尝试一次“适配”,简单的说就是用”()”进行tuple化,如果参数多于一个,将整个TupleN当作参数传入,如果参数为0,则tupling得到一个Unit类型实例传入。
对于scala编译器在方法参数上自作聪明的“适配”,应该严格禁止它发生的可能,建议所有的项目编译时,都开启 -Yno-adapted-args
让编译器给出错误,避免混乱。
一个问题引申诸多细节,很有学习价值。
很难注意到的细节,感谢分享。
感谢分享,已在 build.sbt 中加入 -Yno-adapted-args
debug追一遍的话会好理解得多
很棒的文章 不是洪江大大说以前还不会注意到
Pingback引用通告: scala雾中风景(21): auto-tupling与auto-detupling | 在路上