简体   繁体   English

是否可以使用参数化类型定义返回类型

[英]Is it possible to define a return type with a parameterised type

Say I have the following class and curried function:假设我有以下 class 和咖喱 function:

case class A[T](data: T)

def foo[T](i: Int)(x: T): A[T] 

Then is there any way I can define a function to just call the first part of the previous function?那么有什么办法可以定义一个 function 来调用前面 function 的第一部分? It would be returning a function that takes a parameterised type它将返回一个采用参数化类型的 function

def bar(i: Int) = ... // Can I call foo(i) in some way to return a function: [T](x: T) => A[T]???

Or is it just the case that generic types cannot be used in this way?还是只是泛型类型不能以这种方式使用?

shapeless 2.4.0-M1 can curry polymorphic functions via Curried type class shapeless 2.4.0-M1 可以通过Curried类型 class 柯里化多态函数

scala> import shapeless._
import shapeless._

scala> import poly._
import poly._

scala> case class A[T](data: T)
class A

scala> object foo extends Poly2 {
     |   implicit def default[T] = at[Int, T]((i, x) => A(x))
     | }
object foo

scala> val bar = Poly.curried(foo)
val bar: shapeless.PolyDefns.Curried[foo.type,shapeless.HNil] = Curried(HNil)

scala> bar(42)
val res3: shapeless.PolyDefns.Curried[foo.type,Int :: shapeless.HNil] = Curried(42 :: HNil)

scala> res3(1)
val res4: A[Int] = A(1)

scala> bar(7)
val res5: shapeless.PolyDefns.Curried[foo.type,Int :: shapeless.HNil] = Curried(7 :: HNil)

scala> res5("woohoo")
val res6: A[String] = A(woohoo)

scala> bar("")
          ^
       error: could not find implicit value for parameter cse: shapeless.poly.Case[bar.λ,String :: shapeless.HNil]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM