在Scala中,泛型类型参数可以与* function *定义一起使用吗? [英] In Scala, can generic type parameters be used with *function* definitions?

查看:128
本文介绍了在Scala中,泛型类型参数可以与* function *定义一起使用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种语法允许函数文字上的泛型类型参数?我知道我可以用一个方法来包装它,例如:
$ b $ pre $ def createLongStringFunction [T]():(T)=>布尔= {
(obj:T)=> obj.toString.length> 7
}

但是我最终需要调用每种类型的方法T和获得新功能。我翻看了语言参考,虽然我发现函数文字语法被编译器翻译为一个 Functionn 对象的实例,它本身具有通用输入类型,但它看起来像编译器魔术实现了这些创建时的参数。我没有发现任何允许我实际上让一个或多个 Functionn 的类型参数解除绑定的语法。我更喜欢的是:

  //不会编译
val longStringFunction:[T ](T)=> Boolean =(obj:T)=> obj.toString.length> 7

有没有这样的东西存在?或者就此而言,当扩展的方法具有泛型参数时,eta-expansion函数的显式类型是什么?

这是一个纯粹做作和无用的例子。当然,我可以在这里使用Any。

解决方案

不,类型参数只适用于方法而不适用于函数对象。例如,

  def f [T](x:T)= x //> f:[T](x:T)T 
val g = f _ //> g:Nothing => Nothing =< function1>
// g(2)//错误
val h:Int => Int = f _ //> h:Int => Int =< function2>
h(2)//> res0:Int = 2

方法 f 不能转换为多态函数对象 g 。正如你所看到的, g 的推断类型实际上是 Function1 [Nothing,Nothing] ,这是无用的。然而,对于类型提示,我们可以构造 h:Function1 [Int,Int] ,它符合 Int 参数的预期。


Is there a syntax to allow generic type parameters on function literals? I know I could wrap it in a method such as:

def createLongStringFunction[T](): (T) => Boolean = {
  (obj: T) => obj.toString.length > 7
}

but then I end up needing to invoke the method for every type T and getting a new function. I looked through the language reference, and while I see that the function literal syntax is translated by the compiler to an instance of a Functionn object that itself has generic input types, it looks like the compiler magic realizes those parameters at the time of creation. I haven't found any syntax that allows me to, in effect, "leave one or more of the type parameters of Functionn unbound". What I would prefer is something along the lines of:

// doesn't compile
val longStringFunction: [T](T) => Boolean = (obj: T) => obj.toString.length > 7

Does any such thing exist? Or for that matter, what is the explicit type of an eta-expansion function when the method being expanded has generic parameters?

This is a purely contrived and useless example. Of course I could just make the function use Any here.

解决方案

No, type parameters only apply to methods and not function objects. For example,

def f[T](x: T) = x     //> f: [T](x: T)T
val g = f _            //> g: Nothing => Nothing = <function1>
// g(2)                // error
val h: Int=>Int = f _  //> h  : Int => Int = <function2>
h(2)                   //> res0: Int = 2

The method f cannot be converted to a polymorphic function object g. As you can see, the inferred type of g is actually Function1[Nothing, Nothing], which is useless. However, with a type hint we can construct h: Function1[Int,Int] that works as expected for Int argument.

这篇关于在Scala中,泛型类型参数可以与* function *定义一起使用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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