This page is no longer maintained — Please continue to the home page at www.scala-lang.org

simulating call-by-name with case classes?

1 reply
Ittay Dror 2
Joined: 2010-05-05,
User offline. Last seen 42 years 45 weeks ago.
body p { margin-bottom: 0cm; margin-top: 0pt; }

I want a case class to have a call-by-name argument to its constructor. 

scala> case class Foo(s: => String)
<console>:1: error: `val' parameters may not be call-by-name
       case class Foo(s: => String)

ok, so I try creating an apply method in the companion object:
scala> :paste
// Entering paste mode (ctrl-D to finish)

case class Foo(s: () => String)
object Foo {def apply(s: => String) = new Foo(() => s)}

// Exiting paste mode, now interpreting.

<console>:7: error: double definition:
method apply:(s: () => String)Foo and
method apply:(s: => String)Foo at line 8
have same type after erasure: (s: Function0)$line2.$read#$iw#$iw#Foo
       case class Foo(s: () => String)
                  ^

Of course I can create a regular class, but the class I'm writing is really a value class. Is there another way to achieve what I want?

Regards,
Ittay
Ittay Dror 2
Joined: 2010-05-05,
User offline. Last seen 42 years 45 weeks ago.
Re: simulating call-by-name with case classes?
body p { margin-bottom: 0cm; margin-top: 0pt; }



Ittay Dror wrote:
4EDB8693 [dot] 4050702 [at] gmail [dot] com" type="cite"> body p { margin-bottom: 0cm; margin-top: 0pt; }

I want a case class to have a call-by-name argument to its constructor. 

scala> case class Foo(s: => String)
<console>:1: error: `val' parameters may not be call-by-name
       case class Foo(s: => String)

ok, so I try creating an apply method in the companion object:
scala> :paste
// Entering paste mode (ctrl-D to finish)

case class Foo(s: () => String)
object Foo {def apply(s: => String) = new Foo(() => s)}

// Exiting paste mode, now interpreting.

<console>:7: error: double definition:
method apply:(s: () => String)Foo and
method apply:(s: => String)Foo at line 8
have same type after erasure: (s: Function0)$line2.$read#$iw#$iw#Foo
       case class Foo(s: () => String)
                  ^

Of course I can create a regular class, but the class I'm writing is really a value class. Is there another way to achieve what I want?

My current workaround is to use an implicit argument with a default value of null to disambiguate. Any nicer alternatives?

4EDB8693 [dot] 4050702 [at] gmail [dot] com" type="cite">
Regards,
Ittay

Copyright © 2012 École Polytechnique Fédérale de Lausanne (EPFL), Lausanne, Switzerland