Reputation: 63
I don´t know why it doesn´t work.. I cant use if or when functions in class or in the "playerPosition" function..
class Player(val name:String, val nachname: String, val nr:Int) {
var position = mutableListOf<Int>(0,1,2,3)
var playerPosi = Int
fun playerPosition(){
if(playerPosi < 3 ){
}
}
}
And the next question is, how can I use a function from a class in the main func.? Maybe like this
class Player(val name:String, val nachname: String, val nr:Int, var playerPosi : Int) {
var position = mutableListOf<Int>(0,1,2,3)
fun playerPosition(){
if(playerPosi > 3 ){
println("Diese Position gibt es nicht")
}
}
}
MAIN FUNCTION
fun main(){
val team2 = mutableListOf<Player>()
team2.add(Player("Berkan", "Kutlu", 10,4))
val spieler = Player("Wesley","Sneijder",10,4)
playerPosition()
println("${team2.first().playerPosi}")
}
notice Im trying to set the max Int from playerPosi to 3. Because of Offense, Middfield and Defense and Keeper If Ive the numbers from 0 to 3 I will try to identify 0 as Keeper 1 as Defense and so on.
Thanks for you patience with me :D
Upvotes: 0
Views: 263
Reputation: 1374
The problem here is not the if keyword, it's because the property playerPosi is wrong.
Instead of writing :
var playerPosi = Int
you need to write :
var playerPosi: Int
Why ?
In kotlin, you have two way to declare a variable / property :
After the var / val keyword you give it a name
And after that you have three choices :
var playerPosi = 1
var playerPosi: Int
var playerPosi: Int = 1
If you want to call a method of an object (here it's Player), you need to :
So, if we take your sample :
val team2 = mutableListOf<Player>()
team2.add(Player("Berkan", "Kutlu", 10,4))
val spieler = Player("Wesley","Sneijder",10,4) // Instantiate + take the reference on spieler variable.
speiler.playerPosition() // here you call the playerPosition method with the speiler variable
println("${team2.first().playerPosi}")
Upvotes: 3
Reputation: 85
Try changing from var playerPosi = Int
to var playerPosi: Int
, with :
instead of =
. If you want to define the data type, you should use :
; =
is used to assign value.
To use the function on object you have previously created, you should first specify the object you want the function to be called into, then a dot, and then the function's name. Like this:
fun main(){
val spieler = Player("Wesley","Sneijder",10,4)
spieler.playerPosition()
}
Upvotes: 2
Reputation: 3551
In the first case: var playerPosi = Int
is wrong syntax. Declaration should be var playerPosi: Int
.
In the second case: if player
is object of class Player
, the you can do player.playerPosi
.
main()
function seems to be written for variant #2, where playerPosi
is also constructor parameter.
Upvotes: 1