根据呼叫站点中预期的类型推断方法的返回类型?

时间:2016-04-08 08:10:07

标签: scala

所以,基本上,我想做的是:

object WithoutWrap {

  def f[T: ClassTag](x: String): T = {
    println("Class of T is really… " ++ implicitly[ClassTag[T]].toString)
    ??? : T
  }

  def y: Int = f("abc")
  def z: Int = f[Int]("abc")

}

在这两种情况下,我都希望推断TInt。我们来运行:

scala> WithoutWrap.y
Class of T is really… Nothing
scala.NotImplementedError: an implementation is missing

scala> WithoutWrap.z
Class of T is really… Int
scala.NotImplementedError: an implementation is missing

不幸的是,在第一种情况下它是Nothing

但是,如果我们返回T包裹的东西,

object WithWrap {

  trait Wrap[T]

  def f[T: ClassTag](x: String): Wrap[T] = {
    println("Class of T is really… " ++ implicitly[ClassTag[T]].toString)
    ??? : Wrap[T]
  }

  def y: Wrap[Int] = f("abc")
  def z: Wrap[Int] = f[Int]("abc")

}

...在两种情况下都正确推断T

scala> WithWrap.y
Class of T is really… Int
scala.NotImplementedError: an implementation is missing

scala> WithWrap.z
Class of T is really… Int
scala.NotImplementedError: an implementation is missing

如果在没有包装的情况下如何获得Int

1 个答案:

答案 0 :(得分:1)

根据您尝试完成的操作,重载解析对预期类型敏感:

scala> case class A(s: String) ; case class B(s: String)
defined class A
defined class B

scala> :pa
// Entering paste mode (ctrl-D to finish)

object X {
def f(s: String): A = A(s)
def f(s: String)(implicit d: DummyImplicit): B = B(s)
}

// Exiting paste mode, now interpreting.

defined object X

scala> val x: A = X f "hi"
x: A = A(hi)

scala> val y: B = X f "hi"
y: B = B(hi)