Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala passing type parameters to object

In Scala v 2.7.7

I have a file with

class Something[T] extends Other

object Something extends OtherConstructor[Something]

This throws the error:

class Something takes type parameters
object Something extends OtherConstructor[Something] {

However, I can't do this

object Something[T] extends OtherConstructor[Something[T]]

It throws an error:

error: ';' expected but '[' found.

Is it possible to send type parameters to object? Or should I change and simply use Otherconstructor

like image 206
Shahzad Mian Avatar asked Apr 07 '10 14:04

Shahzad Mian


People also ask

How do I pass an argument to a Scala object?

you can access your Scala command-line arguments using the args array, which is made available to you implicitly when you extend App . As an example, your code will look like this: object Foo extends App { if (args. length == 0) { println("dude, i need at least one parameter") } val filename = args(0) ... }

What is the meaning of => in Scala?

=> is syntactic sugar for creating instances of functions. Recall that every function in scala is an instance of a class. For example, the type Int => String , is equivalent to the type Function1[Int,String] i.e. a function that takes an argument of type Int and returns a String .

What is classOf in Scala?

A classOf[T] is a value of type Class[T] . In other words, classOf[T]: Class[T] . For example: scala> val strClass = classOf[String] strClass: Class[String] = class java. lang. String scala> :t strClass Class[String]

What is type parameter in Scala?

Language. Methods in Scala can be parameterized by type as well as by value. The syntax is similar to that of generic classes. Type parameters are enclosed in square brackets, while value parameters are enclosed in parentheses.


1 Answers

You could use:

object Something extends OtherConstructor[Something[_]]

You will of course be restricted by having an existential type with no upper bound in place instead of a concrete type. This solution may not make sense and you might need one object per concrete type T, for those T's which you care about, e.g.

object StringSomething extends OtherConstructor[Something[String]]

But then this has the (possible) disadvantage that StringSomething is not the companion object of Something.

However, my advice would be don't start messing about designing generic APIs (especially self-referential ones like the above) unless you really, really know what you are doing. It will almost certainly end in tears and there are plenty of CORE Java API's which are terrible because of the way generics have been added (the RowSorter API on JTable being one example)

like image 197
oxbow_lakes Avatar answered Sep 24 '22 12:09

oxbow_lakes