首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Scala / Dotty -将特征混合到现有对象中

Scala / Dotty -将特征混合到现有对象中
EN

Stack Overflow用户
提问于 2020-04-10 14:49:29
回答 3查看 222关注 0票数 4

在Dotty或Scala中,有没有办法将特征混合到现有的对象中?

代码语言:javascript
复制
class SomeClass
trait SomeTrait

// This works, but it's not what I'm looking for:
new SomeClass with SomeTrait

// This is what I'm looking for, but it breaks:
val someClass = new SomeClass
someClass with SomeTrait

This answer提供了一个宏观解决方案,但它已经有7年的历史了,我希望如此(祈祷吧!)为了更简单的东西。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2020-04-10 22:47:49

那么使用类型类来代替呢?

从您在对您的问题的评论中提供的示例:

代码语言:javascript
复制
trait Organism
trait Winged[O <: Organism]
trait Legged[O <: Organism]

class Dog extends Organism
object Dog {
   implicit val legged: Legged[Dog] = new Legged[Dog] { ... }
}

class Fly extends Organism
object Fly {
   implicit val winged: Winged[Fly] = new Winged[Fly] { ... }
   implicit val legged: Legged[Fly] = new Legged[Fly] { ... }
}

这是一种非常灵活的方法,允许您在设计特定有机体时定义LeggedWinged属性,或者稍后通过在相应的伴生对象外部隐式添加它们。您可以通过在伴生对象中提供隐式设置来强制有机体始终具有腿/翅膀,或者将其留给代码的用户。

然后,您可以定义

代码语言:javascript
复制
// Only Winged organisms (ie. `O` for which `Winged[O]` is available implicitly
def makeItFly[O <: Organism : Winged](o: O) 
票数 3
EN

Stack Overflow用户

发布于 2020-04-10 18:14:20

看一下看似废弃但相当新的库zio-delegate

代码语言:javascript
复制
import zio.delegate._

class SomeClass

trait SomeTrait {
  def test() = println("It just works!")
}

val someClass = new SomeClass

val result: SomeClass with SomeTrait =
  Mix[SomeClass, SomeTrait].mix(someClass, new SomeTrait {})

result.test()

它仍然是基于宏的,而且在Scala中使用那样程度的混合是不常见的。Zio完全改变了另一种模式,IIUC。

票数 3
EN

Stack Overflow用户

发布于 2020-04-10 19:05:35

如果你想要类,你仍然需要一个宏

代码语言:javascript
复制
class SomeClass1 extends SomeClass with SomeTrait

将自动生成。

我检查了一下,宏仍然有效(只做了很小的修改)

代码语言:javascript
复制
def toPersisted[T](instance: T, id: Long): T with Persisted = macro impl[T]

def impl[T: c.WeakTypeTag](c: blackbox.Context)(instance: c.Tree, id: c.Tree): c.Tree = {
  import c.universe._

  val typ = weakTypeOf[T]
  val symbol = typ.typeSymbol
  if (!symbol.asClass.isCaseClass)
    c.abort(c.enclosingPosition, s"toPersisted only accepts case classes, you provided $typ")

  val accessors = typ.members.sorted.collect { case x: TermSymbol if x.isCaseAccessor && x.isMethod => x }
  val fieldNames = accessors map (_.name)

  val instanceParam = q"val instance: $typ"
  val idParam = q"${Modifiers(Flag.PARAMACCESSOR)} val id: Long"
  val superArgs = fieldNames map (fieldName => q"instance.$fieldName")
  val ctor =
    q"""def ${termNames.CONSTRUCTOR}($instanceParam, $idParam) = {
      super.${termNames.CONSTRUCTOR}(..$superArgs)
      ()
    }"""
  val idVal = idParam.duplicate
  val tmpl = Template(List(tq"$typ", tq"Persisted"), noSelfType, List(idVal, ctor))
  val cname = TypeName(c.freshName(symbol.name.toString + "$Persisted"))
  val cdef = ClassDef(NoMods, cname, Nil, tmpl)

  q"""
     $cdef
     new $cname($instance, $id)
    """
}

case class MyClass(i: Int, s: String)

val x = MyClass(1, "a")

val y = toPersisted(x, 2L)

y.i // 1
y.s // a
y.id // 2
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61135323

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档