简体   繁体   English

按名称类型参数

[英]By-name type parameters

Imagine I have the following class definition: 想象一下,我有以下类定义:

class Foo[T]

and I want to do the following 我想做以下事情

def bar(x:Foo[ =>Int ]):Int = ???

But compiler fails with "no by-name parameter type allowed here" 但编译器失败,“此处不允许使用by-name参数类型”

How can I use a by-name type as type parameter for a generic method? 如何使用通配名类型作为通用方法的类型参数?

You'll have to provide your own lazy wrapper. 你必须提供自己的懒惰包装。 Something like this: 像这样的东西:

class Lazy[T](wrp: => T) {
  lazy val value: T = wrp
}

and then: 然后:

def bar(x: Foo[Lazy[T]]): Int = ???

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

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