Generic types allow you to define a class with a placeholder type that is specified when instantiating an object. The compiler is happy because it can make sure everything is type safe, and you are happy because you can instantiate an object and pass arbitrary types for the value.
To use a generic type with your class, you can change it as follows:
class CodeRunner[T] (val user_defined: (T) => Unit) { def run(input: T) = { user_defined(input) } }
[T] after "class CodeRunner" is the important part - it determines that there is a general type T (you could replace T with a different capital letter, etc.) that will be used in the class definition.
So, if you define a method:
def arbitrary_code(input: String) = { println("Running with input " + input) }
and then pass it:
val d1 = new CodeRunner(arbitrary_code)
... the compiler then says: "aha, for this CodeRunner instance, the generic type T is a string." And if you call
d1.run("string")
the compiler will be happy, but will not let you go through d1.run (4).
Josh marcus
source share