Reputation: 5206
I'm not sure if the phrasing of the question title was appropriate, so I'll elaborate.
sealed trait RedisKey[A] {
type valueType = A
def name: String
}
case object FirstName extends RedisKey[String] { val name = "first_name" }
case object Age extends RedisKey[Int] { val name = "age" }
trait Redis {
def fetch(key: RedisKey)// : key.valueType
}
I need to constrain the return type of fetch
by RedisKey
's dependent type valueType
(not sure if this is the right term). But obviously, the above wont work since I need a concrete instance of RedisKey
before I can access its dependent type.
Is it possible to achieve this in any way?
Upvotes: 1
Views: 109
Reputation: 714
You can do it with dependent type too:
sealed trait RedisKey {
type valueType
def name: String
}
case object FirstName extends RedisKey { type valueType = String; val name = "first_name" }
case object Age extends RedisKey { type valueType = Int; val name = "age" }
trait Redis {
def fetch(key: RedisKey): key.valueType
}
(null: Redis).fetch(Age): Int
(null: Redis).fetch(FirstName): String
The last two lines are there to test return type of the method in the repl.
Upvotes: 6
Reputation: 5206
Turns out after about 5 minutes after posting this question, I realized I was overthinking this.
The following works without dependent type hackery.
sealed trait RedisKey[A] {
def name: String
}
case object FirstName extends RedisKey[String] { val name = "first_name" }
case object Age extends RedisKey[Int] { val name = "age" }
trait Redis {
def fetch[A](key: RedisKey[A]): A
}
Upvotes: 1