Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"

How can I use a by-name type as type parameter for a generic method?

like image 948
Sane Avatar asked Nov 16 '12 12:11

Sane


People also ask

What are type parameters in Java?

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.

What is type parameter in C#?

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.

What is type parameterization?

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.

What are valid names of a type parameter specified for a class or a method?

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.


1 Answers

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 = ???
like image 165
Jean-Philippe Pellet Avatar answered Sep 25 '22 07:09

Jean-Philippe Pellet