/* * Class definition in Kotlin * * @author gtowell * Created: August 2021 */ // Define a class Numer that has a public property start // and a private property geoff, both integers // // This also creates a constructor that takes one, optional, integer // arguement that sets the value of the property start. class Numer (var start: Int=5) { private val geoff: Int = 7 // when overriding functions, you must use override // single line functions can just do = override fun toString() = String.format("%d %d", start, geoff) fun settle(max:Int) { if (max<=0) { return; } println("%d %s".format(max, this.toString())) settle(max-1) } // Silly method of the class Numer fun s2(max:Int, min:Int, mm:Double, nn: Double) : Int { return max-min } // exactly the same as s2, but using expression syntax and return type inference! fun s2a(max:Int, min:Int, mm:Double, nn: Double) = (max-min) } // to define a property of a class in the primary constructor // the thing MUST be preceded by either var or val!! // So without val/val will get a compilation failure here // as param1 does not exist in the toString function!! class NumerB(val param1:String) { override fun toString() = "%s %s".format(this.javaClass.simpleName, param1) } // function s2 outside the class. Kotlin will not be confused but you might be. fun s2(max:Int, min:Int, mm:Double, nn: Double) : Double { return mm-nn } // again use expression syntax for function defintion fun lesser(p1:Int, p2:Int) = if (p1>p2) { if (p1 > p2*2) { println("double") p1*p1 } else { null } } else { p1.toDouble() } fun main() { val num = Numer(12) println(num) num.start++ println(num.start) num.start++ num.settle(4) num.s2a(2,3,3.4,4.5) val num5 = Numer() println("Num5 " + num5) s2(1,2,4.2, 5.3) var aa = 7.0 println(aa.javaClass.simpleName) println(lesser(3,6)) println(lesser(6,3)) val n2 = NumerB("hello") println(n2) val greet = ::lesser println(greet) }