Type output to formless HList content

This example is simplified.

I have a set of classes like this:

case class KeyMapping[KeyType](k:KeyType)

class WrappedMapping[KeyType](m:T forSome {type T <: KeyMapping[KeyType]}) {
  val k:KeyType = ???
}

In the following code, the types are correctly inferred:

 val w = new WrappedMapping(KeyMapping("key"))

 //The statement below gives the correct error
 //type mismatch; 
 //  found : w.k.type (with underlying type String)  required: Nothing
 //val test1:Nothing = w.k

I do not know how to correctly infer a type for the following:

class Mappings[KeyType, L <: HList](mappings:L) {
  val k:KeyType = ???
}

val m = new Mappings(KeyMapping("key1") :: KeyMapping("key2") :: HNil)

// should not compile, k should be of type String
val test2:Nothing = m.k

Is there any way to make a conclusion KeyTypebased on the content HList?

+4
source share
1 answer

Shapeless provides an implicit ToList, which, unsurprisingly, is used to convert HLists to lists.

To do this, it must first compute the LUB (smallest upper bound) types in the HList and that you can use:

import shapeless.ops.hlist.ToList

class Mappings[L <: HList, Lub](mappings:L)(implicit toList: ToList[L, Lub]) {
  ...
}

L , ( ) ToList, , L, Lub .

, Lub KeyMapping[String], , , String. , :

class Mappings[L <: HList, Lub, KeyType](mappings:L)(
  implicit
  val toList: ToList[L, Lub],
  val kt: Lub <:< KeyMapping[KeyType]
) {
  val k: KeyType = null.asInstanceOf[KeyType]
}

( val s, , , REPL)

, Lub KeyMapping[KeyType] (, ), KeyType . , , KeyType String.

, k, , ToList , mappings.toList

+8

Source: https://habr.com/ru/post/1527298/


All Articles