18

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
}
Amrmsmb
  • 1
  • 27
  • 104
  • 226

4 Answers4

34

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.

name = "ABC" just isn't valid syntax no matter if it's Java or Kotlin. Actually it is (from @hotkey): https://kotlinlang.org/docs/reference/functions.html#named-arguments

TheWanderer
  • 16,775
  • 6
  • 49
  • 63
  • 2
    `name = "ABC"` is actually a correct way to pass the argument in Kotlin, see [Functions / Named Arguments](https://kotlinlang.org/docs/reference/functions.html#named-arguments) in the language reference. – hotkey Sep 09 '18 at 16:47
  • Semicolons are required in Kotlin when you place multiple statements or expressions in a single line of code. – Nikolai Shevchenko Jul 01 '20 at 12:18
3

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
}
Sebastian
  • 1,321
  • 9
  • 21
Aarón Lucker
  • 101
  • 1
  • 1
1

try to forget java

val board = Board("name")
tamtom
  • 2,474
  • 1
  • 20
  • 33
0

in kotlin

when you want to declare new object yon can do like this.

val board = Board("ABC")

if you declare object by using val keyword. it look as you use final in java. the variable which you declared can not recreate again.

var board = Board("ABC")

if you use var to declare it look as normal variable in java

Anyway in kotlin you will see something that It doesn't contain in java such as scoping function as link below. it will help you write your code is more easily.

https://kotlin.guide/scoping-functions

I hope this help :)

Sup.Ia
  • 277
  • 2
  • 8