Cherry
Cherry

Reputation: 33544

How figure out what actual type in scala?

There is one trait with type declaration. I can not figure out what the actual SomeType type is? Here is the code:

package someModel {
    trait SomeTrait extends Serializable {
            type SomeType
            def id: SomeType
        }    
}

Important notes

Upvotes: 0

Views: 97

Answers (2)

Ende Neu
Ende Neu

Reputation: 15783

If I understand your question correctly, SomeType is not an actual type (yet), it's an abstract type member, abstract because the mixing classes will have to provide an implementation for it:

trait SomeTrait extends Serializable {
  type SomeType
  def id: SomeType
}

class SomeClass extends SomeTrait {
  type SomeType = Int

  def id: SomeType = 1
}

class SomeOtherClass extends SomeTrait {
  type SomeType = Long

  def id: SomeType = 2L
}

For difference between generics and type member there's this great SO post

Upvotes: 2

Ryoichiro Oka
Ryoichiro Oka

Reputation: 1997

I don't really understand what "actual type" in your question means.

  1. If you want to know what SomeType is going to be, it's impossible, since it's not declared yet.

  2. If you're asking how to refer to SomeType of some SomeTrait instance during the compile time, then just call foo.SomeType where foo is SomeTrait.

  3. If it's in need during the run time where the type info has been erased, you have to make the instances carry it within something. Here sees how to do it.

I hope I got your idea :)

Upvotes: 1

Related Questions