返回Any时如何保持智能转换的对象类型

时间:2017-05-25 10:39:21

标签: android kotlin kotlin-extension

道歉,如果这是一个愚蠢的问题,Kotlin对我来说还是新手,而且我对语法“类型”不熟悉,因此发现找到解决方案很困难。

fun Any?.test(): Any?
{
    return this
}

"test string".test() // implicit string is now type of "Any"
"test string".test().substring() // what i'm trying to achieve 

我基本上希望类扩展方法返回它自己的实例,所以我仍然可以按照示例的底线操作它

原谅示例的粗鲁,简化了

2 个答案:

答案 0 :(得分:5)

您可以使用generic function

fun <T> T.test(): T {
    return this
}

答案 1 :(得分:1)

你可以使你的扩展功能通用,然后它应该工作。

	var arr=[{"country":"India","languages":[{"languageId":"1", "languageName":"English"},{"languageId":"2", "languageName":"Hindi"},{"languageId":"3", "languageName":"Bengali"}]},
	{"country":"USA","languages":[{"languageId":"1", "languageName":"English"},{"languageId":"4", "languageName":"French"},{"languageId":"5", "languageName":"Italian"}]},
	{"country":"China","languages":[{"languageId":"1", "languageName":"English"},{"languageId":"6", "languageName":"Chinese"},{"languageId":"7", "languageName":"German"}]}];
   function extractLang(arr){
	   var langArr=Array();
	   arr.forEach(function(item, index){
		    var cur_langs=item.languages;
			 cur_langs.forEach(function(lang, ind){
				 if(!langArr.includes(lang.languageName)){
					 langArr.push(lang.languageName);
				 }
			 })
	   });
	   console.log(langArr);
   }
   extractLang(arr);
   //