mirror of
https://github.com/chubin/cheat.sheets
synced 2024-11-01 21:40:24 +00:00
77 lines
1.6 KiB
Plaintext
77 lines
1.6 KiB
Plaintext
// constructor params - private
|
|
class C(x: R) // same as
|
|
class C(private val x: R)
|
|
var c = new C(4)
|
|
|
|
// constructor params - public
|
|
class C(val x: R)
|
|
var c = new C(4)
|
|
c.x
|
|
|
|
class C(var x: R) {
|
|
// constructor is class body
|
|
assert(x > 0, "positive please")
|
|
//
|
|
// declare a public member
|
|
var y = x
|
|
//
|
|
// declare a gettable but not settable member
|
|
val readonly = 5
|
|
//
|
|
// declare a private member
|
|
private var secret = 1
|
|
//
|
|
// alternative constructor
|
|
def this = this(42)
|
|
}
|
|
|
|
// anonymous class
|
|
new{ ... }
|
|
|
|
// define an abstract class. (non-createable)
|
|
abstract class D { ... }
|
|
|
|
// define an inherited class.
|
|
class C extends D { ... }
|
|
class D(var x: R)
|
|
|
|
// inheritance and constructor params. (wishlist: automatically pass-up params by default)
|
|
class C(x: R) extends D(x)
|
|
|
|
// define a singleton. (module-like)
|
|
object O extends D { ... }
|
|
|
|
// traits.
|
|
trait T { ... }
|
|
|
|
// interfaces-with-implementation. no constructor params
|
|
// mixin-able: http://docs.scala-lang.org/tutorials/tour/mixin-class-composition.html
|
|
class C extends T { ... }
|
|
class C extends D with T { ... }
|
|
|
|
// multiple traits.
|
|
trait T1; trait T2
|
|
class C extends T1 with T2
|
|
class C extends D with T1 with T2
|
|
|
|
// must declare method overrides.
|
|
class C extends D { override def f = ...}
|
|
|
|
// create object.
|
|
new java.io.File("f")
|
|
|
|
new List[Int] // BAD type error: abstract type
|
|
List(1,2,3) // GOOD instead, convention: callable factory shadowing the type
|
|
|
|
// class literal.
|
|
classOf[String]
|
|
|
|
// type check (runtime)
|
|
x.isInstanceOf[String]
|
|
|
|
// type cast (runtime)
|
|
x.asInstanceOf[String]
|
|
|
|
// ascription (compile time)
|
|
x: String
|