Kotlin constructors (#4933)

This commit is contained in:
Kacper 2018-08-10 21:10:15 +02:00 committed by Grzegorz Piwowarek
parent 570e33dc1a
commit 4cd349f533
4 changed files with 65 additions and 0 deletions

View File

@ -0,0 +1,17 @@
package com.baeldung.constructor
class Car {
val id: String
val type: String
constructor(id: String, type: String) {
this.id = id
this.type = type
}
}
fun main(args: Array<String>) {
val car = Car("1", "sport")
val s= Car("2", "suv")
}

View File

@ -0,0 +1,3 @@
package com.baeldung.constructor
class Employee(name: String, val salary: Int): Person(name)

View File

@ -0,0 +1,19 @@
package com.baeldung.constructor;
class PersonJava {
final String name;
final String surname;
final Integer age;
public PersonJava(String name, String surname) {
this.name = name;
this.surname = surname;
this.age = null;
}
public PersonJava(String name, String surname, Integer age) {
this.name = name;
this.surname = surname;
this.age = age;
}
}

View File

@ -0,0 +1,26 @@
package com.baeldung.constructor
open class Person(
val name: String,
val age: Int? = null
) {
val upperCaseName: String = name.toUpperCase()
init {
println("Hello, I'm $name")
if (age != null && age < 0) {
throw IllegalArgumentException("Age cannot be less than zero!")
}
}
init {
println("upperCaseName is $upperCaseName")
}
}
fun main(args: Array<String>) {
val person = Person("John")
val personWithAge = Person("John", 22)
}