score:-1

Accepted answer

Since you said you tried on scalafiddle, its not executing anything inside main method.

println("as a script - will be executed")

object x extends App  {
  println("as main app - will not be executed")
}

you probably need to run it as a script as below, working scalafiddle code here - https://scalafiddle.io/sf/3CzSXSp/0

abstract class AbsIterator{
  type T
  def hasNext:Boolean
  def next():T
}

class StringIterator(s:String) extends AbsIterator{
  type T = Char
  private var i = 0
  def hasNext = i < s.length

  def next(): T = {
    val ch = s charAt i
    i += 1
    ch
  }
}

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

class Iter extends StringIterator ("This is a test") with RichIterator
val iter = new Iter
iter foreach println

output

T
h
i
s

i
s

a

t
e
s
t

code - https://scastie.scala-lang.org/prayagupd/UPw6pIqtRPeNlXOr4wDlSw

score:0

App is supposed to be used as a command-line "main" application. When you compile it, and run on command line, JVM finds and executes main method, defined in the App, that executes the code you put into the body of the object. Scala also uses some black magic to prevent the object's body from being executed before main is called.

scalafiddle.io does not do that. It simply executes the code you type there. So, the problem is that you defined the constructor for StringIteratorTest, but never executed it.

If you ran this as a command line application, scala would have done it for you, but on scalafiddle (and other repl-like tools), you have to invoke it explicitly. Adding this line to the end of your script makes it happen: StringIteratorTest.main(Array.empty[String])

score:0

I think scalafiddle doesn't run your App. Try script mode:

https://scalafiddle.io/sf/3GTzp41/1

abstract class AbsIterator {
  type T
  def hasNext:Boolean
  def next():T
}

class StringIterator(s:String) extends AbsIterator {
  type T = Char
  private var i = 0
  def hasNext = i < s.length

  def next()={
    val ch = s charAt i
    i += 1
    ch
  }
}

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

class Iter extends StringIterator ("This is a test") with RichIterator

val iter = new Iter
iter foreach println

Related Query

More Query from same tag