通用嵌套类型推断适用于arity-2,但不适用于curring [英] Generic nested type inference works with arity-2 but not with currying

查看:89
本文介绍了通用嵌套类型推断适用于arity-2,但不适用于curring的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图弄清楚为什么代码对使用arity-2而不是使用currying的方法进行嵌套类型推断的编译.

Trying to figure out why the code compiles for nested type inference on method with arity-2 but not with currying.

object Test
{
    trait Version
    object VersionOne extends Version

    trait Request[A <: Version]
    trait RequestOne extends Request[VersionOne.type]

    case class HelloWorld() extends RequestOne

    def test1[A <: Version, T <: Request[A]](t : T, a : A): T = t
    def test2[A <: Version, T <: Request[A]](t : T)(a : A): T = t
}

// This works
Test.test1(Test.HelloWorld(), Test.VersionOne)

// This doesn't
Test.test2(Test.HelloWorld())(Test.VersionOne)

test2无法编译,并出现以下错误:

test2 fails to compile with the following error:

错误:(22,73)推断的类型参数[Nothing,A $ A96.this.Test.HelloWorld]不符合方法test2的类型参数范围[A< ;: A $ A96.this.Test.Version, T< ;: A $ A96.this.Test.Request [A]] def get $$ instance $$ res1 =/* ### worksheet ###生成的$$ end $$ */Test.test2(Test.HelloWorld())(Test.VersionOne)

Error:(22, 73) inferred type arguments [Nothing,A$A96.this.Test.HelloWorld] do not conform to method test2's type parameter bounds [A <: A$A96.this.Test.Version,T <: A$A96.this.Test.Request[A]] def get$$instance$$res1 = /* ###worksheet### generated $$end$$ */ Test.test2(Test.HelloWorld())(Test.VersionOne)

期待对此有一些见识.

推荐答案

@DmytroMitin已经解释了失败的原因.

@DmytroMitin already explained why it does fail.

但是,您可以使用 部分应用的类型 技巧,以及 通用类型约束 .

However, you can solve the problem this way, using the Partially-Applied Type trick, together with Generalized Type Constraints.

def test2[T](t: T): Test2PartiallyApplied[T] = new Test2PartiallyApplied(t)

final class Test2PartiallyApplied[T](private val t: T) extends AnyVal {
  def apply[A <: Version](a: A)(implicit ev: T <:< Request[A]): T = t
}

您可以像这样使用.

Test.test2(Test.HelloWorld())(Test.VersionOne)
// res: HelloWorld = HelloWorld()

这篇关于通用嵌套类型推断适用于arity-2,但不适用于curring的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆