0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[Scala] 04. Mixin Class Composition

Posted at

Scalaをつかうプロジェクトが始まる予定があり、簡単にScalaの勉強をしようと。

特に話がない内容はScala公式ホームページの内容を基に作成。

Mixin-class Composition

多重相続を実装するため、一般的な目線でクラスを再使用する。

// AbsIterator.scala
abstract class AbsIterator {
    type T
    def hasNext: Boolean
    def next: T
}

// RichIterator.scala
trait RichIterator extends AbsIterator {
    def foreach(f: T => Unit) { while(hasNext) f(next) }
}

// StringIterator.scala
class StringIterator(s: String) extends AbsIterator {
    type T = Char
    private var i = 0
    def hasNext = i < s.length()
    def next = { var ch = s charAt i; i += 1; ch }
}

テスト

// StringIteratorTest.scala
object StringIteratorTest extends App {
    var s: String = "This is a StringIterator's Test"
    class Iter extends StringIterator(s) with RichIterator
    var iter = new Iter
    iter foreach println
}

説明

AbsIterator

type TはIteratorを実装する対象のType

hasNextは次の値があるかどうかを確認するための関数

nextは次の値がある場合、次の値

RichIterator

Iteratorを通じてReturnされる値に適応される関数を定義する

foreach: 各値に何かを適応してくださいとの意味

(f: T => Unit): Tは各値を意味、fは適応する関数、UnitはReturn void

StringIterator

type T: Char

hasNext: 文字列のLengthに比べて次の値があるかを確認

next: hasNextがTRUEの場合、次に位置する文字をnextにする

結果

T
h
i
s
 
i
s
 
a
 
S
t
r
i
n
g
I
t
e
r
a
t
o
r
'
s
 
T
e
s
t
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?