interface - Trying to understand scala trait -
i new scala. don't understand scala traits properly. have read similar java interfaces methods need not abstract. how can declare scala trait , instantiate in following code. btw, following code working fine.
trait fooable { def foo: unit = { println("this foo") } } object main { def main(args: array[string]): unit = { println("this morking") val foo = new fooable{} foo.foo } }
output -
morking foo
thanks in advance.
scala traits more general both java interfaces , abstract classes.
you can use trait interface, can use store implementation, can use define common super-type:
trait message case class text(text: string) extends message case class data(data: bytestring) extends message
multiple traits can 'mixed in' class:
class myclass extends traita traitb traitc
where conflict identically named methods resolved simple rule: last trait takes precedence. code:
trait traita { def print() { println("a") } } trait traitb { def print() { println("b") } } trait traitc { def print() { println("c") } } new myclass.print()
will print "c".
scala traits can't instantiated. creating anonymous class in example. if add abstract method trait not compile.
unrelated note: practice write braces "()" in methods side effects. method foo has side effect: prints something. should write "foo()".
Comments
Post a Comment