By-name type parameters
Asked Answered
V

1

6

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?

Valenevalenka answered 16/11, 2012 at 12:0 Comment(0)
P
10

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 = ???
Permeable answered 16/11, 2012 at 12:6 Comment(3)
what about class Lazy[T](val value: =>T)? No need to repeat the value holder.Adulate
@pedrofurla. not allowed (val parameters may not be call by name). And if it was, at what times would value be supposed to be initialized?Tartuffery
Weird. Didn't know that. I supposed they would be init-ed at first call.Adulate

© 2022 - 2024 — McMap. All rights reserved.