@runzhliu
2018-05-04T01:10:19.000000Z
字数 691
阅读 1604
scala
类型推断
Scala 类型推断算法是非常精巧的,其中之一就是利用了隐式转换来推迟类型解析。Scala 类型推断器会从左到右,推断参数列表,使得前一个参数的类型推断结果能够影响后面的参数的类型推断结果。
来看两个代码块例子。
scala> def foo[A](col: List[A])(f: A => Boolean) = null
foo: [A](col: List[A])(f: A => Boolean)Null
scala> foo(List("String"))(_.isEmpty)
res0: Null = null
foo
方法定义了两个参数列表,分别是 col: List[A]
和 f: A => Boolean
。第一个参数列表接受一个未知类型的列表,第二个参数接受一个使用 A
类型的函数。当不带类型参数调用 foo
方法的时候,调用是成功的,因为编译器能够根据第一个参数的类型,来推断出类型参数 A
是 String
,然后把这个类型应用到第二个参数上,所以编译器就知道了类型参数的类型了,而当把这两个参数合并成一个参数列表的时候,就无法通过编译了。
scala> def foo[A](col: List[A], f: A => Boolean) = null
foo: [A](col: List[A], f: A => Boolean)Null
scala> foo(List("String"), _.isEmpty)
<console>:13: error: missing parameter type for expanded function ((x$1) => x$1.isEmpty)
foo(List("String"), _.isEmpty)