2016-09-20 45 views
2

爲遊戲(包含NPC,玩家,對象等列表的容器)製作EntityContainer時遇到問題。當重寫invoke操作符時,並且在我的代碼被包裝在父lambda中的情況下,我無法添加return語句。Kotin如何在Lambda中包含時指定退貨標籤

import java.util.* 

fun main(args: Array<String>) { 
    val container = Container<String>() 
    container.addList(listOf("h", "e", "l", "l", "o")) 
    container.addList(listOf(" ")) 
    container.addList(listOf("w", "o", "r", "l", "d", "!")) 

    Emptylambda { 
     container[String(), Any(), Any()].forEach { 
      val myCondition = true 
      if (myCondition) [email protected] 

      print(it) 
     } 
    } 

    println("\n\n") 

    Emptylambda { 
     container[String(), Any(), Any()] { 
      val myCondition = true 
      if (myCondition) return //Does not compile 

      print(it) 
     } 
    } 

} 


class Container<E> { 

    private val lists = ArrayList<List<E>>(10) 

    fun addList(list: List<E>) = lists.add(list) 

    fun forEach(action: (E) -> Unit): Unit { 
     lists.forEach { 
      it.forEach { 
       action(it) 
      } 
     } 
    } 

    operator fun invoke(action: (E) -> Unit) = this.forEach { action(it) } 

    operator fun get(vararg ignored: Any): Container<E> { return this } 
} 

object Emptylambda { 
    operator fun invoke(action:() -> Unit) { 
     action() 
    } 
} 

以下是錯誤:

Error:(43, 21) Kotlin: 'return' is not allowed here 

這是一些我寫的輕鬆重現該問題一小部分。一個真實世界的例子如下。

GameScreen { 
    entities[EntityType.PLAYER, EntityType.NPC] { 
      val entity = it 
      if (!entity.isReady()) return //Cant use return here 
      //Draw onto screen 
    } 
} 

回答

相關問題