0
  • Rectangleモジュールが定義されていますが、評価R.lengthおよびR.areaでエラーが発生する理由:値areaはRectangleのメンバーではありません。
  • Rectangleモジュールの定義に改善はありますか?より良いコード?

コード:

class Rectangle(l:Double, w:Double)
{
    require (l>0, w>0)
    val length = l
    val width = w
    def this (l:Double) = this (l, l)
    def area = (length * width)
}

Scalaインタープリター:

class Rectangle(l:Double, w:Double)


[parsing <console>]
[superaccessors in 7ms]
[selectiveanf in 0ms]
[erasure in 4ms]
[Generate ICode from the AST in 5ms]
[inliner in 0ms]
defined class Rectangle


val R = new Rectangle (12, 12)

[parsing <console>]
[erasure in 6ms]
[lazyvals in 0ms]
[Generating icode for <console>]
[Generate ICode from the AST in 4ms]
[inliner in 0ms]
R: Rectangle = Rectangle@117cc9d


val l = println("Rectangle length is " + R.length)

[parsing <console>]
[loaded class file /home/optimight/.eclipse/org.eclipse.platform_3.7.0_155965261/      configuration/org.eclipse.osgi/bundles/201/1/.cp/lib/scala-library.jar(scala/collection/TraversableOnce.class) in 0ms]
[loaded class file /home/optimight/.eclipse/org.eclipse.platform_3.7.0_155965261/configuration/org.eclipse.osgi/bundles/201/1/.cp/lib/scala-library.jar(scala/collection/immutable/IndexedSeq.class) in 0ms]
[total in 44ms]

val A = R.area

[parsing <console>]
<console>:9: error: value area is not a member of Rectangle

この画像は、EclipseScalaIDEのRectangleとscalaインタープリターの完全なコードを示しています。

ご案内ください。

4

1 に答える 1

2

採用のスクリーンショット(ここ)をざっと見てみると、インタプリタで定義したクラスを実際には使用していないようです。インタプリタRectangleの起動時にクラスがロードされ、次のように入力したときにクラスを再定義しますclass Rectangle(l: double, w: double)。クラスがロードされておらず、初めて定義したかのいずれかです。

最初のケースでは、インタープリターに最初の行を入力することを避ける必要があります。2番目のケースでは、クラスをインタープリターにロードする必要があります(scala IDEインタープリターに精通していないため、わかりません。どうやってするの)。

于 2012-06-07T15:42:45.673 に答える