I found two similar codes:
binding.playButton.setOnClickListener (
Navigation.createNavigateOnClickListener(R.id.action_titleFragment_to_gameFragment)
)
binding.playButton.setOnClickListener {
Navigation.findNavController(it).navigate(R.id.action_titleFragment_to_gameFragment)
}
Java code from android view class:
public void setOnClickListener(@Nullable OnClickListener l) {
if (!isClickable()) {
setClickable(true);
}
getListenerInfo().mOnClickListener = l;
}
The question is: how can I create such function where I can use trailing lambda or interface as parameter? I get type mismatch.
interface One {
fun a(): Int
}
class OneImp : One {
override fun a(): Int {
return 4
}
}
fun test(one: One) {
val a = one
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
val a = OneImp()
test (a) //works fine
test {
a //error
}
}
Error:
Type mismatch.
Required:
TitleFragment.One
Found:
() → TitleFragment.OneImp
UPDATE:
After the answer of @Jenea Vranceanu, I have found my error in testing SAM (I used interface from kotlin file, while all the code should be in java). Solution will be: (before kotlinv v1.4 releases) create a java file:
public class Mine {
public interface One {
int a();
}
public class OneImpl implements One {
@Override
public int a() {
return 4;
}
}
public void test(One one) {}
}
Then I can use both function argument and lambda. In kotlin file now:
Mine().test {4}
val b = Mine().OneImpl()
Mine().test (b)
PS. If he adds it to his answer I will delete if from here.