函数之间的互操作

函数之间的互操作

本文介绍了Scala.js 中 js 和 Scala 函数之间的互操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我正在尝试为我的库 Paths.js 编写一个类型化的外观,遵循官方指南.

I am trying to write a typed façade for my library Paths.js, following the official guide.

根据 Sebastien 在 Scala.js 中的 JS 库类型化外观 中的建议,我能够充实部分 API.我现在缺少的是一种处理 API 中公开的转换函数的方法.基本上,该库可以让您编写类似

Following advice from Sebastien in Typed façade for JS library in Scala.js, I was able to flesh out part of the API. What I am now missing is a way to deal with a conversion function which is exposed in the API. Basically, the library lets you write something like

var pie = Pie({
  data: [
    { name: 'Italy', population: 59859996 },
    { name: 'Mexico', population: 118395054 },
    { name: 'France', population: 65806000 }
  ],
  accessor: function(x) { return x.population; },
  center: [20, 15],
  r: 30,
  R: 50
});

这个想法是 - 为了简化客户端代码 - 该库不需要您将数据转换为适合绘图的形式.相反,您可以以您认为合适的形式提供数据列表,然后通过 accessor 函数从原始数据中提取一个数字.这也使得将路径对象与原始数据关联起来更加容易.

The idea is that - to simplify client code - the library does not require you to transform your data to a form that is amenable to plotting. Rather, you can provide a list of data in the form that you see fit, and then pass an accessor function to extract a number from the raw datum. This also makes it easier to associate path objects with the original datum.

我想在 Scala 端公开的签名如下所示:

The signature that I would like to expose on the Scala side would look like this:

object Pie {
  type Point = (Double, Double)
  def apply(data: Seq[A],
    accessor: A => Double,
    center: Point, r: Double, R: Double)
}

我正在尝试转换 accessor,它的类型为 A =>Double 类似于 js.Function1[js.Any, Double],我的尝试看起来像(使用 Function1js 之间的隐式转换.Function1)

I am trying to convert accessor, which has type A => Double to something like js.Function1[js.Any, Double], and my attempt looks like (using the implicit conversion between Function1 and js.Function1)

val f: js.Any => Double = x => x match {
  case _: A => accessor(x)
  case _ => ???
}

这给了我一个警告抽象类型模式 A 未被选中,因为它已被擦除.

翻译此 API 的更好方法是什么?

What would be a better way to translate this API?

推荐答案

在评论中继续讨论:

在这种情况下,使用 js.Function1[A, Double] 是完全有效和合理的.

Using a js.Function1[A, Double] is perfectly valid and reasonable in this case.

正如@sjrd 引用自 Scala.js 文档:

As @sjrd cites from the Scala.js doc:

JS trait 及其方法可以有类型参数、抽象类型成员和类型别名,与 Scala 的类型系统相比没有限制.

这篇关于Scala.js 中 js 和 Scala 函数之间的互操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 21:57