0

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

  • There is no imports in someModel file.
  • Serializable is scala.Serializable
  • type SomeType appear in SomeTrait only. Not somewhere down in the file.
Cherry
  • 31,309
  • 66
  • 224
  • 364

2 Answers2

2

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

Community
  • 1
  • 1
Ende Neu
  • 15,581
  • 5
  • 57
  • 68
1

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 :)

Community
  • 1
  • 1
Ryoichiro Oka
  • 1,949
  • 2
  • 13
  • 20