将 java lambda 谓词移植到 scala

我如何移植

Iterables.filter(tree

                // do the first search using the bounds

                .search(bounds),

                // refine using the exact distance

                entry -> {

                    Point p = entry.geometry();

                    Position position = Position.create(p.y(), p.x());

                    return from.getDistanceToKm(position) < distanceKm;

                });

从 Java 到 Scala?我的以下方法失败了:


import com.github.davidmoten.grumpy.core.Position

import com.github.davidmoten.rtree2.{Iterables, RTree}

import com.github.davidmoten.rtree2.geometry.{Geometries, Point}


val sydney = Geometries.point(151.2094, -33.86)

val canberra = Geometries.point(149.1244, -35.3075)

val brisbane = Geometries.point(153.0278, -27.4679)

val bungendore = Geometries.point(149.4500, -35.2500)


var tree = RTree.star.create[String, Point]

tree = tree.add("Sydney", sydney)

tree = tree.add("Brisbane", brisbane)


val distanceKm = 300

val list = Iterables.toList(search(tree, canberra, distanceKm))


def createBounds(from: Position, distanceKm: Double) = { // this calculates a pretty accurate bounding box. Depending on the

  // performance you require you wouldn't have to be this accurate because

  // accuracy is enforced later

  val north = from.predict(distanceKm, 0)

  val south = from.predict(distanceKm, 180)

  val east = from.predict(distanceKm, 90)

  val west = from.predict(distanceKm, 270)

  Geometries.rectangle(west.getLon, south.getLat, east.getLon, north.getLat)

}


因为类型entry似乎没有明确定义。


侃侃无极
浏览 142回答 1
1回答

喵喵时光机

tree类型RTree[String, Point]为T=String, S=Point. 所以tree.search(bounds)有 type Iterable[Entry[String, Point]]。所以entry有 type Entry[String, Point]。尝试(entry: Entry[String,Point]) => {&nbsp; def foo(entry: Entry[String,Point]) = {&nbsp; &nbsp; val p = entry.geometry&nbsp; &nbsp; val position = Position.create(p.y, p.x)&nbsp; &nbsp; from.getDistanceToKm(position) < distanceKm&nbsp; }&nbsp; foo(entry)})在 Scala 2.13.0、rtree2 0.9-RC1、grumpy-core 0.2.4 中测试。在 2.11 中,这应该只是import scala.compat.java8.FunctionConverters._((entry: Entry[String,Point]) => {&nbsp; def foo(entry: Entry[String,Point]) = {&nbsp; &nbsp; val p = entry.geometry&nbsp; &nbsp; val position = Position.create(p.y, p.x)&nbsp; &nbsp; from.getDistanceToKm(position) < distanceKm&nbsp; }&nbsp; foo(entry)}).asJavalibraryDependencies += "org.scala-lang.modules" %% "scala-java8-compat" % "0.9.0"
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java