logo
Tags down

shadow

Should I use nested classes in this case?


By : user15662
Date : March 29 2020, 07:55 AM
With these it helps I would be a bit reluctant to use nested classes here. What if you created an abstract base class for a "multimedia driver" to handle the back-end stuff (workhorse), and a separate class for the front-end work? The front-end class could take a pointer/reference to an implemented driver class (for the appropriate media type and situation) and perform the abstract operations on the workhorse structure.
My philosophy would be to go ahead and make both structures accessible to the client in a polished way, just under the assumption they would be used in tandem.
code :


Share : facebook icon twitter icon

Using nested case classes with scodec


By : harish525
Date : March 29 2020, 07:55 AM
I wish did fix the issue. I figured it out. You need to use the Codec, not the HList. This works:
code :
object Bar {
  //Foo.codec instead of Foo.baseCodec
  val baseCodec = uint8 :: Foo.codec :: uint16
  val codec = baseCodec.as[Bar]
}

Converting nested case classes to nested Maps using Shapeless


By : Joemt
Date : March 29 2020, 07:55 AM
may help you . Any time you want to perform an operation like flatMap on an HList whose type isn't statically known, you'll need to provide evidence (in the form of an implicit parameter) that the operation is actually available for that type. This is why the compiler is complaining about missing FlatMapper instances—it doesn't know how to flatMap(identity) over an arbitrary HList without them.
A cleaner way to accomplish this kind of thing would be to define a custom type class. Shapeless already provides a ToMap type class for records, and we can take it as a starting point, although it doesn't provide exactly what you're looking for (it doesn't work recursively on nested case classes).
code :
import shapeless._, labelled.FieldType, record._

trait ToMapRec[L <: HList] { def apply(l: L): Map[String, Any] }
trait LowPriorityToMapRec {
  implicit def hconsToMapRec1[K <: Symbol, V, T <: HList](implicit
    wit: Witness.Aux[K],
    tmrT: ToMapRec[T]
  ): ToMapRec[FieldType[K, V] :: T] = new ToMapRec[FieldType[K, V] :: T] {
    def apply(l: FieldType[K, V] :: T): Map[String, Any] =
      tmrT(l.tail) + (wit.value.name -> l.head)
  }
}

object ToMapRec extends LowPriorityToMapRec {
  implicit val hnilToMapRec: ToMapRec[HNil] = new ToMapRec[HNil] {
    def apply(l: HNil): Map[String, Any] = Map.empty
  }

  implicit def hconsToMapRec0[K <: Symbol, V, R <: HList, T <: HList](implicit
    wit: Witness.Aux[K],
    gen: LabelledGeneric.Aux[V, R],
    tmrH: ToMapRec[R],
    tmrT: ToMapRec[T]
  ): ToMapRec[FieldType[K, V] :: T] = new ToMapRec[FieldType[K, V] :: T] {
    def apply(l: FieldType[K, V] :: T): Map[String, Any] =
      tmrT(l.tail) + (wit.value.name -> tmrH(gen.to(l.head)))
  }
}
implicit class ToMapRecOps[A](val a: A) extends AnyVal {
  def toMapRec[L <: HList](implicit
    gen: LabelledGeneric.Aux[A, L],
    tmr: ToMapRec[L]
  ): Map[String, Any] = tmr(gen.to(a))
}
scala> p.toMapRec
res0: Map[String,Any] = Map(address -> Map(zip -> 10000, street -> Jefferson st), name -> Tom)

Nested Scala case classes to/from CSV


By : user1727514
Date : March 29 2020, 07:55 AM
Hope this helps Since a case-class is a Product, getting the values of the various fields is relatively easy. Getting the names of the fields/columns does require using Java reflection. The following function takes a list of case-class instances and returns a list of rows, each is a list of strings. It is using a recursion to get the values and headers of child case-class instances.
code :
def toCsv(p: List[Product]): List[List[String]] = {
  def header(c: Class[_], prefix: String = ""): List[String] = {
    c.getDeclaredFields.toList.flatMap { field =>
      val name = prefix + field.getName
      if (classOf[Product].isAssignableFrom(field.getType)) header(field.getType, name + ".")
      else List(name)
    }
  }

  def flatten(p: Product): List[String] =
    p.productIterator.flatMap {
      case p: Product => flatten(p)
      case v: Any => List(v.toString)
    }.toList

  header(classOf[Match]) :: p.map(flatten)
}
def fromCsv[T <: Product](csv: List[List[String]])(implicit tag: ClassTag[T]): List[T] = {
  trait Instruction {
    val name: String
    val header = true
  }
  case class BeginCaseClassField(name: String, clazz: Class[_]) extends Instruction {
    override val header = false
  }
  case class EndCaseClassField(name: String) extends Instruction {
    override val header = false
  }
  case class IntField(name: String) extends Instruction
  case class StringField(name: String) extends Instruction
  case class DoubleField(name: String) extends Instruction

  def scan(c: Class[_], prefix: String = ""): List[Instruction] = {
    c.getDeclaredFields.toList.flatMap { field =>
      val name = prefix + field.getName
      val fType = field.getType

      if (fType == classOf[Int]) List(IntField(name))
      else if (fType == classOf[Double]) List(DoubleField(name))
      else if (fType == classOf[String]) List(StringField(name))
      else if (classOf[Product].isAssignableFrom(fType)) BeginCaseClassField(name, fType) :: scan(fType, name + ".")
      else throw new IllegalArgumentException(s"Unsupported field type: $fType")
    } :+ EndCaseClassField(prefix)
  }

  def produce(instructions: List[Instruction], row: List[String], argAccumulator: List[Any]): (List[Instruction], List[String], List[Any]) = instructions match {
    case IntField(_) :: tail => produce(tail, row.drop(1), argAccumulator :+ row.head.toString.toInt)
    case StringField(_) :: tail => produce(tail, row.drop(1), argAccumulator :+ row.head.toString)
    case DoubleField(_) :: tail => produce(tail, row.drop(1), argAccumulator :+ row.head.toString.toDouble)
    case BeginCaseClassField(_, clazz) :: tail =>
      val (instructionRemaining, rowRemaining, constructorArgs) = produce(tail, row, List.empty)
      val newCaseClass = clazz.getConstructors.head.newInstance(constructorArgs.map(_.asInstanceOf[AnyRef]): _*)
      produce(instructionRemaining, rowRemaining, argAccumulator :+ newCaseClass)
    case EndCaseClassField(_) :: tail => (tail, row, argAccumulator)
    case Nil if row.isEmpty => (Nil, Nil, argAccumulator)
    case Nil => throw new IllegalArgumentException("Not all values from CSV row were used")
  }

  val instructions = BeginCaseClassField(".", tag.runtimeClass) :: scan(tag.runtimeClass)
  assert(csv.head == instructions.filter(_.header).map(_.name), "CSV header doesn't match target case-class fields")

  csv.drop(1).map(row => produce(instructions, row, List.empty)._3.head.asInstanceOf[T])
}
case class Player(name: String, ranking: Int, price: Double)
case class Match(place: String, winner: Player, loser: Player)

val matches = List(
  Match("London", Player("Jane", 7, 12.5), Player("Fred", 23, 11.1)),
  Match("Rome", Player("Marco", 19, 13.54), Player("Giulia", 3, 41.8)),
  Match("Paris", Player("Isabelle", 2, 31.7), Player("Julien", 5, 16.8))
)
val csv = toCsv(matches)
val matchesFromCsv = fromCsv[Match](csv)

assert(matches == matchesFromCsv)

Convert Nested Case Classes to Nested Maps in Scala


By : D Davis
Date : March 29 2020, 07:55 AM
Any of those help As Luigi Plinge notes in a comment above, this is a very bad idea—you're throwing type safety out the window and will be stuck with a lot of ugly casts and runtime errors.
That said, it's pretty easy to do what you want with the new Scala 2.10 Reflection API:

Can't get pureconfig to deserialize nested case classes


By : PPr
Date : March 29 2020, 07:55 AM
wish helps you You should always annotate implicit definitions, especially in situations like this, where the derivation of the reader for ClassA depends on the one for ClassB, etc. The following just works:
code :
import com.typesafe.config.{Config, ConfigFactory}
import pureconfig.ConfigReader
import pureconfig.error.ConfigReaderFailures
import pureconfig.generic.ProductHint
import pureconfig.generic.semiauto._
import pureconfig.{CamelCase, ConfigFieldMapping}

class ClassAReader {
  implicit def classAHint: ProductHint[ClassA] =
    ProductHint[ClassA](ConfigFieldMapping(CamelCase, CamelCase))
  implicit def classBHint: ProductHint[ClassB] =
    ProductHint[ClassB](ConfigFieldMapping(CamelCase, CamelCase))

  implicit val classAReader: ConfigReader[ClassA] = deriveReader[ClassA]
  implicit val classBReader: ConfigReader[ClassB] = deriveReader[ClassB]

  def read(config: Config): Either[ConfigReaderFailures, ClassA] =
    pureconfig.loadConfig[ClassA](config)
}

case class ClassA(a: ClassB, b: ClassB, other: Int)
case class ClassB(one: Int, two: String)
scala> val config = ConfigFactory.parseString(
     |   """{ a: { one: 1, two: "foo" }, b: { one: 2, two: "bar" }, other: 42 }"""
     | )
config: com.typesafe.config.Config = Config(SimpleConfigObject({"a":{"one":1,"two":"foo"},"b":{"one":2,"two":"bar"},"other":42}))

scala> val reader = new ClassAReader
reader: ClassAReader = ClassAReader@589da48f

scala> reader.read(config)
res1: Either[pureconfig.error.ConfigReaderFailures,ClassA] = Right(ClassA(ClassB(1,foo),ClassB(2,bar),42))
Related Posts Related Posts :
  • Compiling standard library types
  • Sending argument to an .exe via SHELLEXECUTEINFO
  • Why I can't use i/10 in FOR LOOP, C++?
  • How to use PERF_SAMPLE_READ with mmap
  • Is there any way to iterate through a struct?
  • My character counting code is miscounting characters. Why?
  • Difference between std::resize(n) and std::shrink_to_fit in C++?
  • Wildcard for C++ concepts saying "accepting anything for this template argument"
  • Which of the objects of the class A would be created first in this code snippet?
  • Floating point math accuracy, c++ vs fortran
  • C++ initialize objects with packed array of integers
  • Picking a constructor to call
  • using function call in constructor gives different result c++
  • Using strcpy to copy elements of an char array to another array
  • Templated Constructor Specialization
  • Struggling to convert an integer into a linked list. Not sure what I'm doing wrong here
  • C++: Is it better to store a console output in a macro?
  • C++ - Exception in Constructor
  • AVX: matrix dot vector, but ignore diagonal
  • Pointer To Pointer passed by reference
  • Why is this operator< overload function invisible to STL algorithms?
  • What is the correct algorithm to perform double-float division?
  • In the case of using a std::unique_ptr to automatically deallocate memory upon exiting a scoped block, why not just use
  • C++: Iterating over a string vector and using the index for putenv
  • OpenCL Matrix Multiplication Using std::vector
  • template template parameter deduction: three different compilers three different behaviors
  • C++ pull a card from deck
  • File reading with and without new line
  • store strings in stable memory in c++
  • Why is static_cast used in QT's official document
  • iterator .end() from std::list returns "0xcdcdcdcdcdcdcdcd" but .begin() as expected
  • Is std::sqrt the same as sqrt in C++
  • Iterate through std::initializer_list
  • Codeblocks c++ code doesn't run in VS 19 (vector subscript out of range)
  • Why erase on std::vector promote iterator
  • how to destroy an object in C++
  • How to create Visual Studio 2015 solution from CMake
  • Using concepts for checking if a type T has a field F
  • constructor giving error: no matching function for call to
  • search top n% of a vector member C++
  • Is this reinterpret_cast problematic in principle, and/or in practice?
  • What is the following error doing? I do not see any error with the bounds
  • Two index's of an array have same memory adress
  • how do i avoid integer division in c++?
  • Setting value to enum
  • Properties of a pointer to a zero length array
  • Why the output is different how ever the formula is the same?
  • Restarting from the beginning using do while loops
  • Error: invalid initialization of reference of type
  • how to avoid to use memcpy to create a string
  • Copying the vector elements into std::array
  • Is there any class pointers in Perl in order to access member variables and functions?
  • Why the static variable is not set to 1000
  • Why can't a destructor have reference qualifiers?
  • How to print binary tree in horizontal way?
  • Comparison behavior of ' <' operator
  • Constructors in C++ Language
  • Why displayed value of b , c and y is different from my trace?
  • Undefined reference to `fftw_init_threads' while installing pHash library
  • Reading remapped hdd sectors
  • shadow
    Privacy Policy - Terms - Contact Us © voile276.org