case-class

Scala copy case class with generic type

假如想象 提交于 2021-02-07 05:27:05
问题 I have two classes PixelObject , ImageRefObject and some more, but here are just these two classes to simplify things. They all are subclasses of a trait Object that contains an uid. I need universal method which will copy a case class instance with a given new uid . The reason I need it because my task is to create a class ObjectRepository which will save instance of any subclass of Object and return it with new uid . My attempt: trait Object { val uid: Option[String] } trait UidBuilder[A <:

Prohibit generating of apply for case class

血红的双手。 提交于 2021-02-07 02:53:30
问题 I'm writing a type-safe code and want to replace apply() generated for case class es with my own implementation. Here it is: import shapeless._ sealed trait Data case object Remote extends Data case object Local extends Data case class SomeClass(){ type T <: Data } object SomeClass { type Aux[TT] = SomeClass { type T = TT } def apply[TT <: Data](implicit ev: TT =:!= Data): SomeClass.Aux[TT] = new SomeClass() {type T = TT} } val t: SomeClass = SomeClass() // <------------------ still compiles,

Retrieve value from Some in scala

为君一笑 提交于 2020-08-08 08:42:06
问题 I am trying to retrieve case object used for creating enum from string Taking reference from Extracting field from Some in Scala sealed trait Mapping {def code: Int;def desc: Symbol} object types { case object TypeA extends Mapping { val code = 0; val desc = 'A } case object TypeB extends Mapping { val code = 1; val desc = 'B } val values=List(TypeA,TypeB) def getType(desc: Symbol) = values.find(_.desc == desc) } The below code makes me able to retrive value back from Some(TypeA) var s=types

Scala polymorphic callback type mismatch

我与影子孤独终老i 提交于 2020-07-22 06:08:11
问题 I'm sorry i couldn't find a better title. I'm trying to achieve something like the following abstract class Person case class User(uid: String, firstname: String, active: String) extends Person case class Admin(id: String, pseudo: String, securityClearance: String) extends Person def innerFunctionForUser(user: User): List[String] = { List() :+ user.uid :+ user.firstname :+ user.active } def innerFunctionForAdmin(admin: Admin): List[String] = { List() :+ admin.id :+ admin.psuedo :+ admin

Case class to map in Scala

最后都变了- 提交于 2020-07-10 10:27:03
问题 Is there a nice way I can convert a Scala case class instance, e.g. case class MyClass(param1: String, param2: String) val x = MyClass("hello", "world") into a mapping of some kind, e.g. getCCParams(x) returns "param1" -> "hello", "param2" -> "world" Which works for any case class, not just predefined ones. I've found you can pull the case class name out by writing a method that interrogates the underlying Product class, e.g. def getCCName(caseobj: Product) = caseobj.productPrefix getCCName(x