Scala 根据调用站点中预期的类型推断方法的返回类型?

Scala 根据调用站点中预期的类型推断方法的返回类型?,scala,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") } 在这两种情况下,我希望推断的T为Int。让我们运行这个

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

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")

}
在这两种情况下,我希望推断的
T
Int
。让我们运行这个:

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
不幸的是,在第一种情况下,它什么都不是

但是,如果我们返回包在某物中的
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
,而无需包装?

根据您试图完成的任务,重载解析对预期类型敏感:

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)

是的,根据方法的返回类型推断类型可能很棘手。我有一个相似的,可能有相同的(或至少相关的)原因
Wrap[T]
是类型
T
的不变量,
Wrap[Int]
的唯一子类型是
Wrap[Int]
本身!!!您可以将
Wrap[T]
更改为
Wrap[+T]
以进行验证。@Eastsun,哦……对……那么……我想……没有办法了=(就
T
而言,它采用了最具体的
T
子类型,即
nothing
。对吗?我认为这是不可能的。