java - Scala IntList 到 Java
问题描述
所以我有这个 Scala 函数,它返回一个 IntList
def drawLine(x0: Int, y0: Int, x1: Int, y1: Int): IntList = {
val list : IntList = drawLineRec(x0, y0, x1, y1, Math.abs(x1-x0), -Math.abs(y1-y0), Math.abs(x1-x0)-Math.abs(y1-y0))
println("\nline: "+list)
return list
}
我现在想在我的 java 文件中使用它,在这里我调用这个函数并获得返回
CalcDraw.IntList drawLine = newDraw.drawLine(x0, y0, x1, y1);
有没有办法在 java 中运行这个 IntList,因为我尝试使用for
or foreach
,但没有任何运气。
返回调用包含如下内容:
Cons((20,20),Cons((21,21),Nil()))
编辑更多信息
所以这里是一个简化的 Scala 代码:
class CalcDraw { // ctrl + shift+ b to evaluate.
sealed abstract class IntList;
case class Nil() extends IntList;
case class Cons(hd: (Int,Int), tl: IntList) extends IntList;
def concat(list1: IntList, list2: IntList) : IntList = list1 match{
//concatenates two lists
case Nil() => list2
case Cons(head,tail) => Cons(head,concat(tail,list2))
}
def concatIf(list1: IntList, list2: IntList, predicate: ()=>Boolean) : IntList = if(predicate()){
concat(list1,list2)
}else{
return list1
}
/*
*
* LINE DRAWING
*
*/
def next(x0: Int, x1: Int): Int = if(x0 < x1) x0 + 1 else x0 - 1
def drawLineRec(x0: Int, y0: Int, x1: Int, y1: Int, dx: Int, dy: Int, err: Int): IntList = {
if(!(x0 == x1 && y0 == y1))
{
if((2*err) >= dy)
{
if((2*err) <= dx)
{
// Change in both x and y0
Cons((x0, y0), drawLineRec(next(x0, x1), next(y0, y1), x1, y1, dx, dy, err + dx + dy))
}
else
{
// Change only in x0
Cons((x0, y0), drawLineRec(next(x0, x1), y0, x1, y1, dx, dy, err + dy))
}
}
else if((2*err) <= dx) {
// Change only in y0
Cons((x0, y0), drawLineRec(x0, next(y0, y1), x1, y1, dx, dy, err + dx))
} else{
Nil() // This should not happen, so maybe this is an incorrect approach
}
} else{
Cons((x0, y0), Nil())
}
}
def drawLine(x0: Int, y0: Int, x1: Int, y1: Int): IntList = {
val list : IntList = drawLineRec(x0, y0, x1, y1, Math.abs(x1-x0), -Math.abs(y1-y0), Math.abs(x1-x0)-Math.abs(y1-y0))
println("\nline: "+list)
return list
}
}
java部分就像调用函数一样简单
CalcDraw.IntList drawLine = newDraw.drawLine(x0, y0, x1, y1);
解决方案
你可以做:
CalcDraw calcDraw = new CalcDraw();
CalcDraw.IntList l = calcDraw.drawLine(1, 2, 3, 4);
while (l instanceof CalcDraw.Cons) {
CalcDraw.Cons cons = (CalcDraw.Cons) l;
System.out.println(cons.hd());
l = cons.tl();
}
另外,请阅读Scala 中的 Return,这里不应该使用它。您可以删除分号。你可能想定义IntList
为sealed trait
. 您可以在使用密封特征和密封抽象类作为基类的区别中阅读更多信息
推荐阅读
- angular - Angular 5:如何从具有checked = true属性的数组中获取要在编辑组件上选中的复选框?
- python - Initializing state on dask-distributed workers
- php - 有 XML 的 SQL 吗?
- javascript - Angular 7导入所有但忽略一个文件
- android - 以编程方式重新初始化后,线性布局内的视图无法正确显示
- nginx - 具有相似前缀的 nginx 位置
- java - 新标签导航有时不加载页面,为什么?
- c - SDL Init 在代码正确且之前运行完美时减慢程序
- c++ - Simplest way to determine if current assembly is 32/64bit within the code
- ssl - 如何解决 Jenkins 插件安装问题?