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"
How can I use a by-name type as type parameter for a generic method?
A type parameter, also known as a type variable, is an identifier that specifies a generic type name. The type parameters can be used to declare the return type and act as placeholders for the types of the arguments passed to the generic method, which are known as actual type arguments.
The type parameter is a placeholder for a specific type that the client specifies when they create an instance of the generic type. A generic class cannot be used as-is because it is simply a blueprint for that type.
Type parameterization allows you to write generic classes and traits. For example, sets are generic and take a type parameter: they are defined as Set[T] . As a result, any particular set instance might be a Set[String] , a Set[Int] , etc. —but it must be a set of something.
Type Parameter Naming Conventions The most commonly used type parameter names are: E - Element (used extensively by the Java Collections Framework) K - Key. N - Number.
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 = ???
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With