简体   繁体   English

Scala中的类型类API

[英]Type class API in Scala

This is a pattern I am considering to use in Scala to define a contract without limiting the type but still having a fluent API without all the verbose implicity[..]. 我正在考虑在Scala中使用这种模式来定义合同,而不限制类型,但仍具有流畅的API,而没有所有冗长的隐式[..]。

The idea is to build a implicit class on top of a type class like so: 这个想法是在类型类之上构建一个隐式类,如下所示:

implicit class NumberLikeApi[N : NumberLike](n: N)
  def add(n2: N): N = implicitely[NumberLike[N]].add(n, n2)
}

Now with the right implicits in scope you can do: 现在,使用合适的隐式范围,您可以执行以下操作:

val sum = n1.add(n2)

Instead of: 代替:

val sum = implicitly[NumberLike[N]].add(n1, n2)

My question: Is it somehow possible to automate / generate the implicit class part? 我的问题:是否有可能自动/生成隐式类部分? It is basically a duplication of the type class. 它基本上是类型类的重复。

I failed to find something in the language & standard library. 我在语言和标准库中找不到任何内容。 Is there perhaps a macro in a library somewhere that can do this? 库中是否有某个宏可以执行此操作?

The purpose of simulacrum should be exactly this. simulacrum的目的应该就是这样。

From its README, you can write 从其自述文件中,您可以编写

import simulacrum._

@typeclass trait Semigroup[A] {
  @op("|+|") def append(x: A, y: A): A
}

and then use it like 然后像

// instance for Semigroup[Int] 
implicit val semigroupInt: Semigroup[Int] = new Semigroup[Int] {
  def append(x: Int, y: Int) = x + y
}

import Semigroup.ops._

1 |+| 2 // 3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM