package Implicit
object ImplicitTest {
implicit val stringModoId: ModoId[String] = new ModoId[String] {
override def add(x: String, y: String): String = {
x.concat(y)
}
override def unit: String = {
""
}
}
implicit val intModoId: ModoId[Int] = new ModoId[Int] {
override def add(x: Int, y: Int): Int = {
x + y
}
override def unit: Int = {
0
}
}
def sum[A](result: List[A])(implicit m: ModoId[A]): A = {
if (result.isEmpty) {
m.unit
} else {
m.add(result.head, sum(result.tail))
}
}
def main(args: Array[String]): Unit = {
println(sum(List(1, 2, 3)))
println(sum(List("a", "b", "c")))
}
}
abstract class ModoId[A] {
def add(x: A, y: A): A
def unit: A
}
Mixs
package Implicit
abstract class A {
val message: String
}
class B extends A {
override val message: String = "I'm an instance of class B"
}
trait C extends A {
def loudMessage = message.toUpperCase()
}
class D extends B with C {
}
abstract class AbsInterator {
type T
def hasNext: Boolean
def next: T
}
class StringIterator(s: String) extends AbsInterator {
override type T = Char
private var i = 0
override def hasNext: Boolean = {
i < s.length
}
override def next: Char = {
val ch = s charAt(i)
i += 1
ch
}
}
trait RichIterator extends AbsInterator {
def foreach(f: T => Unit): Unit = while(hasNext) {f(next)}
}
class RichStringIter extends StringIterator("hello") with RichIterator
object test {
def main(args: Array[String]): Unit = {
/*val d: D = new D()
println(d.message)
println(d.loudMessage)*/
val richStringIter: RichStringIter = new RichStringIter()
richStringIter.foreach(x => println(x))
}
}