I am trying to achieve something with Shapeless' HMap, but am not sure whether this is possible and if it is, then how would I go about it.
I want to use HMap as a map of user preferences where values can be of different types. This is what I mean:
object UserPreferences {
sealed abstract class BooleanPreference
case object IsStudent extends BooleanPreference
case object SubscribedToNotifications extends BooleanPreference
sealed abstract class StringPreference
case object Language extends StringPreference
class UserPreference[K, V]
implicit val booleanPreferenceToBoolean = new UserPreference[BooleanPreference, Boolean]
implicit val stringPreferenceToString = new PartialClientPref[StringPreferenceKey, String]
}
Then later on I have this map as a method argument:
import UserPreferences._
def someMethod(userPreferences: HMap[UserPreference]) {
val userLanguage = userPreferences(Language)
}
The last code snippet doesn't compile. First it complaints about missing implicit parameter, but when I add stringPreferenceToString explicitly the compiler indicates that it requires UserPreference[UserPreferences.Language.type, NotInferredV] but found UserPreference[StringPreference, String]
CodePudding user response:
You need to widen Language to a StringPreference and import userPreferences._.
import UserPreferences._
def someMethod(userPreferences: HMap[UserPreference]) {
import userPreferences._
val userLanguage = userPreferences(Language: StringPreference)
}
