how to instantiate an object from a class in kotlin
Solution 1
Kotlin does not use new
.
Board board = new Board(name = "ABC");
is incorrect. Use
val board = Board("ABC")
Your code reflects the Java syntax... sort of. Kotlin has type inference, so you don't need to specify the class type. However, if you do specify it, it's different from Java:
val board: Board = Board("ABC")
Semi-colons are also not generally used in Kotlin, although they won't break the compilation if you use them.
Actually it is (from @hotkey): https://kotlinlang.org/docs/reference/functions.html#named-argumentsname = "ABC"
just isn't valid syntax no matter if it's Java or Kotlin.
Solution 2
Unlike Java, in Kotlin this is the correct way
MainActivity.kt
class ActMain : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.layout_act_main)
val board = Board("ABC")
board.age = 12
}
}
Board.kt
class Board(val name: String) {
var age: Int = 0
}
Solution 3
try to forget java
val board = Board("name")
LetsamrIt
Updated on July 13, 2022Comments
-
LetsamrIt almost 2 years
I am learning Kotlin, and I googled how to create a class in kotlin. So, I created the below class as a test. In the main activity, I am trying to instantiate an object from the class Board, but i get the following error:
classifier Board does not have a companion object
please let me know how to intantiate an object of an the class Board?
MainActivity:
class ActMain : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.layout_act_main) Board board = new Board(name = "ABC"); } }
Board.kt:
data class Board(val name: String) { var age: Int = 0 }
-
hotkey over 5 years
name = "ABC"
is actually a correct way to pass the argument in Kotlin, see Functions / Named Arguments in the language reference. -
Nikolai Shevchenko almost 4 yearsSemicolons are required in Kotlin when you place multiple statements or expressions in a single line of code.