1

I want to get actual type class from Generic type.

When I try this

I get class scala.runtime.Nothing only.

import scala.reflect._ class Car { } object Car extends Model[Car] { } trait Model[T] { def something[T:ClassTag]():Unit = { println(classTag[T].runtimeClass) } } Car.something() // <- scala.runtime.Nothing$ 
1
  • 2
    The two Ts are different. Try: Car.something[String]() for example. Commented Dec 26, 2014 at 21:14

3 Answers 3

3

You might want something like the following: The T=:=U would unify the two types and the :ClassTag would just create a ClassTag for it.

Edit: the correct, but still too complicated form:

trait Model[T] { def something[U](implicit ev: T =:= U, tag: ClassTag[U]): Unit = { println(tag.runtimeClass) } 

In general, I would also use https://stackoverflow.com/a/27666845/1502148 (when I am not sleepy :) ).

Sign up to request clarification or add additional context in comments.

1 Comment

This is 1) not a legal syntax; 2) more complicated than required if you fix the syntax to def something[U](implicit ev: T =:= U, tag: ClassTag[U]).
2
class Model[T:ClassTag] { def something():Unit = { println(classTag[T].runtimeClass) } } 

I solved by modifying Model trait to class and provide ClassTag to Generic.

Comments

1

If you want to allow creating a Model without ClassTag and only require ClassTag for some methods, you can do

trait Model[T] { def something(implicit tag: ClassTag[T]):Unit = ... } 

Obviously this applies to e.g. Numeric, Ordering, etc. constraints as well.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.