首页 > 解决方案 > 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,因为我尝试使用foror 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);

标签: javascala

解决方案


你可以做:

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,这里不应该使用它。您可以删除分号。你可能想定义IntListsealed trait. 您可以在使用密封特征和密封抽象类作为基类的区别中阅读更多信息


推荐阅读