Skip to content

Commit 4cd349f

Browse files
kacperkozapivovarit
authored andcommitted
Kotlin constructors (eugenp#4933)
1 parent 570e33d commit 4cd349f

4 files changed

Lines changed: 65 additions & 0 deletions

File tree

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
package com.baeldung.constructor
2+
3+
class Car {
4+
val id: String
5+
val type: String
6+
7+
constructor(id: String, type: String) {
8+
this.id = id
9+
this.type = type
10+
}
11+
12+
}
13+
14+
fun main(args: Array<String>) {
15+
val car = Car("1", "sport")
16+
val s= Car("2", "suv")
17+
}
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
package com.baeldung.constructor
2+
3+
class Employee(name: String, val salary: Int): Person(name)
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
package com.baeldung.constructor;
2+
3+
class PersonJava {
4+
final String name;
5+
final String surname;
6+
final Integer age;
7+
8+
public PersonJava(String name, String surname) {
9+
this.name = name;
10+
this.surname = surname;
11+
this.age = null;
12+
}
13+
14+
public PersonJava(String name, String surname, Integer age) {
15+
this.name = name;
16+
this.surname = surname;
17+
this.age = age;
18+
}
19+
}
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package com.baeldung.constructor
2+
3+
open class Person(
4+
val name: String,
5+
val age: Int? = null
6+
) {
7+
val upperCaseName: String = name.toUpperCase()
8+
9+
init {
10+
println("Hello, I'm $name")
11+
12+
if (age != null && age < 0) {
13+
throw IllegalArgumentException("Age cannot be less than zero!")
14+
}
15+
}
16+
17+
init {
18+
println("upperCaseName is $upperCaseName")
19+
}
20+
21+
}
22+
23+
fun main(args: Array<String>) {
24+
val person = Person("John")
25+
val personWithAge = Person("John", 22)
26+
}

0 commit comments

Comments
 (0)