小编Kam*_*och的帖子

使用泛型重载Scala方法

带有两个重载方法编译的示例代码(Scala 2.11.8),如预期的那样:

def foo(p: Int, t: Double): Unit = {}
def foo(r: Int => Double): Unit = {}

foo(0, 0) // 1st method
foo(x => x.toDouble) // 2nd method
Run Code Online (Sandbox Code Playgroud)

添加了通用参数的相同代码:

def fooGeneric[T](p: T, t: Double): Unit = {}
def fooGeneric[T](r: T => Double): Unit = {}

fooGeneric[Int](1, 1) // 1st method
fooGeneric[Int]((x: Int) => x.toDouble) //2nd method

fooGeneric[Int](x => x.toDouble) // does not compile
Run Code Online (Sandbox Code Playgroud)

产生以下编译错误:

Error:(112, 19) missing parameter type
fooGeneric[Int](x => x.toDouble)
Run Code Online (Sandbox Code Playgroud)

方法解析似乎没有歧义,但编译器无法找到匹配项.为什么?

generics scala overloading

5
推荐指数
0
解决办法
267
查看次数

Scala 2 类型推断

def test[T: ClassTag]: T = {
  println(classTag[T])
  null.asInstanceOf[T]
}
val x1: Int = test
val x2: Int = test[Int]
Run Code Online (Sandbox Code Playgroud)

印刷

Nothing
Int
Run Code Online (Sandbox Code Playgroud)

我希望编译器能够猜测Int类型,而无需显式提供它(编辑:在右侧,即使工作val x1: Int = test)。

是否有解决方法可以摆脱显式类型注释?

scala type-inference

0
推荐指数
1
解决办法
118
查看次数

标签 统计

scala ×2

generics ×1

overloading ×1

type-inference ×1