1. 반환값이 없는 함수

 

fun myFunction(fname: String, age: Int) {
  println(fname + " is " + age)
}

fun main() {
  myFunction("John", 35)
  myFunction("Jane", 32)
  myFunction("George", 15)
}

// John is 35
// Jane is 32
// George is 15

 

 

 

 

 

2. 반환값이 있는 함수

 

fun myFunction(x: Int, y: Int): Int {
  return (x + y)
}

fun main() {
  var result = myFunction(3, 5)
  println(result)
}

// 8 (3 + 5)

 

 

 

 

 

3. 기본 예제 클래스

 

class Car {
  var brand = ""
  var model = ""
  var year = 0
} 

val c1 = Car()
c1.brand = "Ford"
c1.model = "Mustang"
c1.year = 1969

val c2 = Car()
c2.brand = "BMW"
c2.model = "X5"
c2.year = 1999

println(c1.brand)  // Ford
println(c2.brand)  // BMW

 

 

 

 

 

4. 생성자가 있는 클래스

 

class Car(var brand: String, var model: String, var year: Int)

fun main() {
  val c1 = Car("Ford", "Mustang", 1969)
  val c2 = Car("BMW", "X5", 1999)
  val c3 = Car("Tesla", "Model S", 2020)

  println(c1.brand) // Ford
  println(c2.brand) // BMW
  println(c3.brand) // Tesla
  
  c2.year = 2023
  println("new model : " + c2.year) // new model : 2023
}

 

 

 

 

 

5. 매개변수가 있는 클래스

 

class Car(var brand: String, var model: String, var year: Int) {
  // Class function
  fun drive() {
    println("Wrooom!")
  }

  // Class function with parameters
  fun speed(maxSpeed: Int) {
    println("Max speed is: " + maxSpeed)
  }
  
  // 
  fun changeYear(newYear: Int) {
    year = newYear
  }
}

fun main() {
  val c1 = Car("Ford", "Mustang", 1969)
  
  // Print property values
  println(c1.brand + " " + c1.model + " " + c1.year) // Ford Mustang 1969
  
  // Call the functions
  c1.drive() // Wrooom!
  c1.speed(200) // Max speed is: 200
  println(c1.year) // 1969
  c1.changeYear(2023)
  println(c1.year) // 2023
}

 

 

 

 

 

6. 클래스 상속 예제 1

 

// Superclass
open class MyParentClass {
  var x = 5
}

// Subclass
class MyChildClass: MyParentClass() {
  fun myFunction() {
    println(x) // x is now inherited from the superclass
  }
}

// Create an object of MyChildClass and call myFunction
fun main() {
  val myObj = MyChildClass()
  myObj.myFunction() // 5
  myObj.x = 10
  myObj.myFunction() // 10
}

 

 

 

 

 

7. 클래스 상속 예제 2

 

open class Animal {
  var name: String = "animal 1"
}

class DogClass : Animal() {
  fun resetName(newName: String) {
    name = newName
  }
  fun sayWow() {
    println("$name says Wow~")
  }
  fun introduceYourselfWithAge(age: Byte): String {
    return "I'm $name and I'm $age years old."
  }
}

// Create an object of MyChildClass and call myFunction
fun main() {
  var myDog = DogClass()
  myDog.resetName("dogdogi")
  myDog.sayWow()
  myDog.resetName("MongMong")
  val introducing = myDog.introduceYourselfWithAge(15)
  println(introducing)
}

 

 

 

+ Recent posts