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

Type parameters as member methods.

3 replies
edmondo1984
Joined: 2011-09-14,
User offline. Last seen 28 weeks 3 days ago.
Dear all,assuming I have an abstract class with an abstract type T.
Can I imagine to have a builder method that receives a concrete type for T, and builder a concrete instance of the class?
Best Regards
Edmondo
Derek Williams 3
Joined: 2011-08-12,
User offline. Last seen 42 years 45 weeks ago.
Re: Type parameters as member methods.
On Fri, Jan 6, 2012 at 10:40 AM, Edmondo Porcu <edmondo [dot] porcu [at] gmail [dot] com> wrote:
Dear all,assuming I have an abstract class with an abstract type T.
Can I imagine to have a builder method that receives a concrete type for T, and builder a concrete instance of the class?
Best Regards
Edmondo

You either need to use reflection, or you can use a type class:
trait Builder[T] {  def build(): T}
object Builder {  def build[T](implicit builder: Builder[T]): T = builder.build()}
class MyClass {  def foo = "bar"}

object MyClass {   implicit builder: Builder[MyClass] = new Builder[MyClass] {    def build: MyClass = new MyClass  }}
def exampleMethod[T: Builder] = {  val myT = Builder.build[T]   println("I've built a " + myY)}

--
Derek Williams
H-star Development
Joined: 2010-04-14,
User offline. Last seen 2 years 26 weeks ago.
Re: Type parameters as member methods.

Am 06.01.2012 18:40, schrieb Edmondo Porcu:
> Dear all,
> assuming I have an abstract class with an abstract type T.
>
> Can I imagine to have a builder method that receives a concrete type
> for T, and builder a concrete instance of the class?
>
> Best Regards
>
> Edmondo
like that?

object TypedBuilder {
abstract class Foo {
type bar
val foobar: bar
}

def build[X](x:X) = new Foo {
type bar = X
val foobar = x
}

def main(args: Array[String]) {
val foo = build("yes it works")
val bar = build(12345)
println(foo + bar.toString)
}
}

afaik types exist only at compile time

Tim P
Joined: 2011-07-28,
User offline. Last seen 1 year 4 weeks ago.
Re: Type parameters as member methods.

Edmondo
I had a similar problem a month or two back only more complicated -
with generic builders and concrete builders etc. If you want to check
it out follow this:

https://groups.google.com/group/scala-user/browse_thread/thread/120fb7f4...

to the end and check out Miles Sabin's solution.

Tim

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